jquery ajax forms for ASP.NET MVC 3

前端 未结 1 2028
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 01:22

this might be an easy question but for me right now it is not clear and I have to get things sorted in my head... maybe somebody can help me with that =)...

I know t

1条回答
  •  天涯浪人
    2020-12-13 01:36

    Ajax.BeginForm() is this then MvcAjax or Jquery?

    By default it is jquery. You need to reference the jquery.unobtrusive-ajax.js script for this to work.

    Or would I use Html.BeginForm() and register something like $.post on the click event of the Form.

    That's an alternative. Personally that's what I do.

    I assume that it is correct, that I am posting to the create action of the commentscontroller and I would use the JsonModelBinder to transform it to a model. After that I would return Json and would append it to my comments list...

    The JsonModelBinder has been introduced in ASP.NET MVC 3 and it allows you to send a JSON string to a controller action which will be mapped back to a view model. For example if you have the following view model:

    public class PersonViewModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    

    and the following action:

    public ActionResult Foo(PersonViewModel person) 
    {
        ...    
    }
    

    the traditional way to invoke it in AJAX is:

    $.ajax({
        url: '@Url.Action("foo")',
        type: 'POST',
        data: { name: 'john', age: 20 },
        success: function(result) {
            // TODO:
        }
    });
    

    and in ASP.NET MVC 3 you could send a JSON as request parameter which will be bound to the PersonViewModel action parameter:

    $.ajax({
        url: '@Url.Action("foo")',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ name: 'john', age: 20 }),
        success: function(result) {
            // TODO:
        }
    });
    

    0 讨论(0)
提交回复
热议问题