Problem performing Ajax call from ASP.NET MVC2 app

微笑、不失礼 提交于 2019-12-01 20:40:39

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!