ASP.NET MVC 4: enabling XmlHttpRequest message for controller with $ .ajax ()

Seems simple, but I've been looking around the world all day with a bit of regression! Please help. I have a simple post request to an MVC controller ...

 $(document).ready(function () {
    $('#json_request').on("click", function () {
        // send request to server for menu json data
        $.ajax({
            type: "POST", 
            url: location.protocol + "//" + location.host + "/Tablet/Menu",
            data: { restaurantId: $('#restaurantId option:selected').val(), mealSessionId: $('#mealSessionId option:selected').val() },
            success: function (menuData) {alert(menuData); },
            error: function () { alert("failed"); }
        });
    });
});

      

The request just won't reach the controller! The app works fine when I submit the request as an Html form. It works great with Visual Studio development server. I am getting 404 error with IIS 7.0 / ASP.NET / MVC 4. Maybe contentType: application / x-www-form-urlencoded is not getting through http protocol filters. Do I have to install them specifically? How? Thank you for your help. I am not sending the request as json, so I have not tried contentType: application / json.

Controller / Action:

[HttpPost]
    public ActionResult Menu(short restaurantId, short mealSessionId)
    {
        try
        {
            MenuInput menuInput = new MenuInput(restaurantId, mealSessionId);
            menuInput.LoadMenu();
            if (Request.IsAjaxRequest())
            {
                MemoryStream ms = new MemoryStream();
                menuInput.AsJson(ms);
                string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                JsonResult result = Json(jsonString, "text/x-json");
                ms.Close();
                return result;
            }
            else
            {
                return View("MenuInformation", menuInput);
            }
        }
        catch (Exception ex)
        {
            System.Console.Write(ex.ToString());
            return View();
        }
    }

      

+3


source to share





All Articles