Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem performing Ajax call from ASP.NET MVC2 app

I'm converting an existing ASP.NET app to MVC2, and I have an existing method that is called through jQuery using Ajax, that worked before, but does not work now. So it seems there are some change I need to do due to using MVC2 that I can't figure out.

I have reduced the complexity of the code, but it still do not work. This is my current code:

jQuery script that trigger on button click

function leaveComment() {
if (validate()) {
    $.ajax({
        type: "POST",
        url: "/Pages/PostBlogComment",
        data: "{'name':'Test','url':'Test','email':'Test','body':'Test','postid':'Test'}",
        dataType: "json",
        success: function (msg) {
            //success code goes here
        },
        error: function (msg) {
           //error code goes here
        }
    });
}

};

Inside my controller called Pages, I have created the following method:

public string PostBlogComment( string name, string url, string email, string body, string postid)
{
  return "This is a test";
}

When debugging I can see that the PostBlogComment method gets called, but there are two major problems I'm facing here:

  1. All arguments to the method is received as null, so I have no useful data to work with. For testing now, all arguments are sent as Test as you can see from the code.
  2. When returning the result to the Ajax method, the error path is called, and not the success path, even it the method did return the string as normal (even if the parameters sent in was blank)

The error is probably easy to spot for those who work with these things regularly (or at least I hope so :))

like image 862
Øyvind Bråthen Avatar asked Dec 28 '22 23:12

Øyvind Bråthen


1 Answers

Here are the changes you need to make this work:

$.ajax({
    type: 'POST',
    url: '/Pages/PostBlogComment',
    data: { 
        name: 'Test', 
        url: 'Test', 
        email: 'Test', 
        body: 'Test', 
        postid: 'Test'
    },
    success: function (result) {
        alert(result.Value);
    },
    error: function (msg) {
       //error code goes here
    }
});

and your controller action

public ActionResult PostBlogComment( 
    string name, 
    string url, 
    string email, 
    string body, 
    string postid
)
{
    return Json(new { Value = "This is a test" });
}

Which could be improved by introducing a view model:

public class PostViewModel
{
    public string Name { get; set; }
    public string Url { get; set; }
    public string Email { get; set; }
    public string Body { get; set; }
    public string Postid { get; set; }
}

and then:

public ActionResult PostBlogComment(PostViewModel model)
{
    return Json(new { Value = "This is a test" });
}

Things to note:

  1. the data hash property of a jquery AJAX call needs to be as my example or you would be sending a JSON encoded string and the default model binder of ASP.NET MVC doesn't know how to parse back as action arguments. In ASP.NET MVC 3 this has changed as there is a JsonValueProviderFactory allowing you to send JSON requests. So if you were using ASP.NET MVC 3 you could send your AJAX request like this and the action parameters will be correctly bound:

    $.ajax({
        type: 'POST',
        url: '/Pages/PostBlogComment',
        data: JSON.stringify({ 
            name: 'Test', 
            url: 'Test', 
            email: 'Test', 
            body: 'Test', 
            postid: 'Test'
        }),
        contentType: 'application/json',
        success: function (result) {
            alert(result.Value);
        },
        error: function (msg) {
           //error code goes here
        }
    });
    
  2. All controller actions in ASP.NET MVC must return ActionResults. So if you want Json then return a JsonResult.

  3. The action passes an anonymous type to the Json method containing a Value property which is used in the success callback and the response from the server would look like this:

    { 'Value': 'This is a test' }
    
  4. Never hardcode urls like this in your javascript files or your application might break when you deploy it. Always use Url helpers when dealing with urls:

    ...
    url: '<%= Url.Action("PostBlogComment", "Pages") %>',
    ...
    

    or if this was an external javascript file you could either use some global js variable that was initialized in your view pointing to the correct url or make this url as part of your DOM (for example as anchor href property or HTML5 data-* attributes) and then use jQuery to fetch the value.

like image 146
Darin Dimitrov Avatar answered Jan 03 '23 00:01

Darin Dimitrov