Using Ajax.BeginForm with ASP.NET MVC 3 Razor

后端 未结 8 1014
面向向阳花
面向向阳花 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
    
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    
    <div id="result"></div>
    
    @using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
    {
        @Html.EditorFor(x => x.Foo)
        @Html.ValidationMessageFor(x => x.Foo)
        <input type="submit" value="OK" />
    }
    

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

    View:

    @model AppName.Models.MyViewModel
    
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>
    
    <div id="result"></div>
    
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.Foo)
        @Html.ValidationMessageFor(x => x.Foo)
        <input type="submit" value="OK" />
    }
    

    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.

    0 讨论(0)
  • 2020-11-22 01:56

    Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,

    1. jquery-1.7.1.min.js
    2. jquery.unobtrusive-ajax.min.js

    Only these two are enough for performing Ajax operation.

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