DrBowe
DrBowe

Reputation: 115

jQuery Ajax failing to call to MVC 4 Controller method

I'm attempting to use jQuery in order to fire off an Ajax call after clicking a certain button. I've read several examples of the syntax and issues that may be encountered, but have failed to find a working solution for my cause. Here's the code.

Controller Method: (HomeController.cs)

    [HttpPost]
    public JsonResult ChangeCompany(string companyCode)
    {
        return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
    }

jQuery Code:

    function changeCompany(company) {
    $.ajax({
        url: '@Url.Action("ChangeCompany", "Home")',
        type: 'POST',
        data: JSON.stringify({ companyCode: company }),

        success: function (data) {
            alert("Company: " + data);
        },
        error: function (req, status, error) {
            alert("R: " + req + " S: " + status + " E: " + error);
        }
    });
}

And finally, I'm calling this function with:

$('.companyButton').click(function () {
    compCode = $(this).text();
    debug("Click event --> " + $(this).text());
    changeCompany(compCode);
});

My debug message displays properly, and the Ajax call constantly fails with the following alert: R: [object Object] S: error E: Not Found

I'm not entirely sure what to make of that.

I know there are several questions on this topic, but none of them seem to resolve my issue and I'm honestly not sure what's wrong with these code blocks. Any insight would be appreciated.

EDIT: In case it's worth noting, this is for a mobile device. Testing on Windows 8 Phone Emulator (Internet Explorer), alongside jQuery Mobile. Not sure if that affects Ajax at all

EDIT 2: After taking a look at the raw network call, it seems that 'Url.Action("ChangeCompany", "Home")' is not being converted into the proper URL and is instead being called directly as if it were raw URL text. Is this due to an outdated jQuery, or some other factor?

Upvotes: 5

Views: 14039

Answers (3)

Chamika Sandamal
Chamika Sandamal

Reputation: 24312

Ok with your EDIT2 it seems you are using url: '@Url.Action("ChangeCompany", "Home")', in a separate JavaScript file. you can only write the razor code inside the .cshtml file and it is not working inside the .js files

Upvotes: 6

InspiredBy
InspiredBy

Reputation: 4320

Note that your action is not returning companyCode directly. You're assigning it to Json result property therefore In your success function to display result you need to have:

success: function (data) 
  {
     alert("Company: " + data.result);
  }

Also this: E: Not Found tells me that you may have some routing issues. If you set a break point inside of your ChangeCompany Action, is it being hit ?

Upvotes: 0

Bhushan Firake
Bhushan Firake

Reputation: 9458

You are missing some important parameters in your AJAX call. Change your AJAX call as below:

function changeCompany(company) {
    $.ajax({
              url: '@Url.Action("ChangeCompany", "Home")',
              type: 'POST',
              data: JSON.stringify({ companyCode: company }), 
              success: function (data) {
                       alert("Company: " + data);
                        },
             error: function (req, status, error) {
                       alert("R: " + req + " S: " + status + " E: " + error);
                        }
          });}

You can then annotate your controller method with [HttpPost] attribute as below;

 [HttpPost]
 public JsonResult ChangeCompany(string companyCode)
 {
   return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
 }

Upvotes: 1

Related Questions