MVC Ajax Form & Ajax Valida(笔记)
1、引入必要的文件
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
2、Ajax From & Ajax Valida
<h2>AjaxForm</h2> <!--两种loading 方式,一种是 ajax form 提供的 LoadingElementId(loading 对象起始设置display:none;),另外一种是在 onBegin 开启Loading效果,然后再OnComplete关闭Loading效果--> @using (Ajax.BeginForm("ajax", "home", new AjaxOptions() { LoadingElementId = "loading", UpdateTargetId = "ajaxResult", OnComplete = "return OnComplete()", OnBegin = "return OnBegin();", Confirm = "要提交?", OnFailure = "return OnFailure();", OnSuccess = "OnSuccess" })) { <text>Name:</text><input type="text" id="name" name="name" data-val="true" data-val-required="Name 是必填项." /> @*<span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true" style="font-size:large; color:blue;"></span>*@ @Html.Partial("_ValidationError","name") <br /> <text>Age:</text><input type="text" id="age" name="age" data-val="true" data-val-required="Age 是必填项." data-val-digits="输入合法数字."/> @Html.Partial("_ValidationError","age") <br /> <text>Email:</text><input type="text" id="email" name="email" data-val="true" data-val-email="Email格式不正确."/> @Html.Partial("_ValidationError","email") <br /> <input type="submit" value="Ajax提交" /> <br /> } <div id="ajaxResult"> </div> <div id="loading" style="display:none;"> 正在请求,请稍后.......... </div> <script> function OnComplete() { //alert("OnComplete 事件"); $("h2").html("AjaxForm"); } function OnBegin() { //alert("OnBegin 事件"); $("h2").html("请在请求,请稍后...") } function OnFailure() { alert("OnFailure 事件 - ajax请求失败"); } function OnSuccess(data) { //alert("ajax 请求成功返回的数据:" + data); } </script>
3、Controllers
public ActionResult AjaxForm() { return View(); } [HttpPost] public ActionResult ajax(string name, string age) { //throw new Exception("内部抛出了异常"); return PartialView("AjaxFromControl", new AjaxModel() { Name = name, Age = age}); }