Using Ajax.BeginForm with ASP.NET MVC 3 Razor

后端 未结 8 1030
面向向阳花
面向向阳花 2020-11-22 01:23

Is there a tutorial or code example of using Ajax.BeginForm within Asp.net MVC 3 where unobtrusive validation and Ajax exist?

This is an elusive topic f

8条回答
  •  时光取名叫无心
    2020-11-22 01:50

    Example:

    Model:

    public class MyViewModel
    {
        [Required]
        public string Foo { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return Content("Thanks", "text/html");
        }
    }
    

    View:

    @model AppName.Models.MyViewModel
    
    
    
    
    
    
    @using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" })) { @Html.EditorFor(x => x.Foo) @Html.ValidationMessageFor(x => x.Foo) }

    and here's a better (in my perspective) example:

    View:

    @model AppName.Models.MyViewModel
    
    
    
    
    
    
    @using (Html.BeginForm()) { @Html.EditorFor(x => x.Foo) @Html.ValidationMessageFor(x => x.Foo) }

    index.js:

    $(function () {
        $('form').submit(function () {
            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            }
            return false;
        });
    });
    

    which can be further enhanced with the jQuery form plugin.

提交回复
热议问题