Home > .NET, JQuery, MVC, Vs2012 > MVC Ajax with IIS 7.5 and with VS Server

MVC Ajax with IIS 7.5 and with VS Server

2013/10/23

I’m not an Visual Studio 2012 Development Server (also of IIS Express…) fan, for a lot of motivations.

An example is a difference in the default paths for an MVC jQuery Ajax call , if is done from the VS dev server or from Windows 7 IIS 7.5 (i will investigate on IIS under Windows 8…) , which is near identical to the IIS on the average, real production server.

In order to see this difference create an simple MVC4 project (as Internet Application) named HelloWorld ; in the Models folder create a class UserData , as

namespace HelloWorld.Models
{
    public class UserData
    {
        public string UserName { get; set; }
    }
}

in the HomeController.cs created by default (using the Internet application template) place a method GetMessage

[HttpGet]
public JsonResult GetMessage(UserData myData)
{
    myData.UserName = "Hello " + myData.UserName ;
    return Json(myData, JsonRequestBehavior.AllowGet);
}

In the Scripts folder place an HelloWorld.js script:

var myData = {
    UserName: "Bill Gates"
};
$(function () {
    $.ajax({
        type: "GET",
        url: "/Home/GetMessage",
        data: myData,
        contentType: "application/json",
        success: processResult
    });
});
 
function processResult(returnedData) {
    window.alert("Returned value : " + returnedData.UserName);
}

We are using the HomeController so we use “Home” (without “Controller”) as address.

Our javascript can be referenced in Index.cshtml adding after the last line

@section scripts{
   <script src="~/Scripts/HelloWorld.js">
   </script> 
}

Launching the site we receive


At this point in the solution properties the web server we change from the Visual Studio Development Server to IIS (not Express) , creating in IIS a new Web Application that uses the ASP.NET v4.0 Application Pool


This time launching the application is no more used the address localhost:4560 but the IIS application, and our script is no more working : using Fiddler we can see that there is an 404 error.

If in the javascript we change the URL from

url: “/Home/GetMessage”,

To

url: “/HelloWorld/Home/GetMessage”,

(that is we add the application name) our app turns back to working, but does not work if we revert the solution to use the Visual Studio Development Server.

There is a trick, changing the VirtualPath to from the single “/” to “/HelloWorld” (the name given to the IIS 7.5 web application and used in the Ajax url)


The Visual Studio web application is still working as the true IIS version.

Advertisements
Categories: .NET, JQuery, MVC, Vs2012
%d bloggers like this: