一、引入必要的文件javascript
<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>
二、Ajax From & Ajax Validahtml
<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>
三、Controllersjava
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}); }