On the Index page, I show a list of employees, when the user clicks the Edit link, I show View View.
This edit view displays a partial view (_EditPartial) to display the various fields that are being edited.
When the user clicks the Save button, I want to make an Ajax post.
I want to check the input before sending the data to the server. I tried using unobtrusive checks, but validation does not work for me. Below is a snippet of code.
ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are included in the web.config file.
Code snippet
Partial View Code
@model WebApplication1.Models.employee <div id="mypartial" class="form-horizontal"> <h4>employee</h4> <hr /> @Html.ValidationSummary(true) @Html.HiddenFor(model => model.id) <div class="form-group"> @Html.LabelFor(model => model.name, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.name) @Html.ValidationMessageFor(model => model.name) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.age, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.age) @Html.ValidationMessageFor(model => model.age) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.address, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.address) @Html.ValidationMessageFor(model => model.address) </div> </div> </div>
====================
Change view code @model WebApplication1.Models.employee
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Edit</title> <script src="~/Scripts/jquery-2.1.0.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnSave").click(function () { $("#btnSave").click(function () { debugger; </script> </head> <body> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.Partial("_EditPartial", Model) <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="button" id="btnSave" value="Save" class="btn btn-default" /> </div> </div> } </body> </html>
=============
Action code
[HttpPost] public ActionResult Edit([Bind(Include="id,name,age,address")] employee employee) { // This return falase because input data is invalid if (ModelState.IsValid) { db.SaveChanges(); return RedirectToAction("Index"); } return View(employee); }
================
Model
part-time public employee {public servant () {this.employeerolemappings = new List (); }
public int id { get; set; } [Required] public string name { get; set; } [Required] public Nullable<int> age { get; set; } [Required] public string address { get; set; }
}
I check the displayed html code. data-val = "true" comes with differet fields.
Can anyone help how to use client validation using ajax post call.
jquery asp.net-mvc razor asp.net-mvc-4 unobtrusive-validation
Atul sureka
source share