By default, Visual Studio 2013 creates a new ASP. MVC5 project that does not contain jquery.unobtrusive-ajax.js and needs to be added manually.
Click the Tools menu in Visual Studio 2013, select Library Package Manager, select Manage NuGet packages for your solution, search for jquery.unobtrusive-ajax.js Online in the dialog box that appears, and then install.
Fancy information, corresponding version is 3.2.0, need to jQuery1.8 above version support. The jQuery1.10.2 that are included by default in MVC5 can satisfy the criteria.
Next, we can use the ajaxhelper.
View Code:
@model mvclearning.models.setpasswordmodel@{viewbag.title="Change Password";}<script type="Text/javascript"Src="@Url. Content ("~/scripts/jquery-1.10.2. js")"></script><script type="Text/javascript"Src="@Url. Content ("~/scripts/jquery.unobtrusive-ajax.js")"></script> <script type="Text/javascript">function Show (msg) {alert (msg); }</script>@using (Ajax.beginform ("Edit",NewAjaxoptions () {onsuccess="Show"}) {@Html. AntiForgeryToken ()<br/> <divclass="Form-horizontal">@Html. ValidationSummary (true) <divclass="Form-group">@Html. Labelfor (Model= Model. Password,New{@class ="Control-label col-md-2" }) <divclass="col-md-10">@Html. Passwordfor (Model=model. Password) @Html. Validationmessagefor (Model=model. Password)</div> </div> <divclass="Form-group"> <divclass="col-md-offset-2 col-md-10"> <input type="Submit"Value="Save" class="btn Btn-default"/> </div> </div> </div>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval")}
Don't forget to reference the script in view:
<script type= text/javascript " src=" @ Url.content ( ~/scripts/jquery-1.10 . 2 . Js ) ></script><script type=" text/javascript " Src= " @Url. Content ( " ~/scripts/ Jquery.unobtrusive-ajax.js ) " ></script>
Controller code:
[HttpPost] PublicActionResult Edit (Setpasswordmodel model) {Try { stringUsername=User.Identity.Name; varUser= db. User.where (x = X.username = =userName). FirstOrDefault (); if(model. password!=user. Password) {Modelstate.addmodelerror ("","Original Password Error! "); returnView (model); } Else{User. Password= Model. NewPassword;//Update Passworddb. SaveChanges (); returnContent ("Password modified successfully! "); } //return redirecttoaction ("Index", "Contactgroup"); } Catch { returnView (model); } }
You can also return JavaScript directly in the controller with the following code:
The View code is modified as follows:
@using (Ajax.beginform ("Edit", New Ajaxoptions ()))
The controller code is modified as follows:
Return JavaScript ("alert (' Password modified successfully!") ‘);");
ASP. MVC5 using Ajaxhelp