Model:
public class CarModel { public int Id { get; set; } public string ImageFileName { get; set; } [Required(ErrorMessage = "Name is Requried")] [StringLength(32, ErrorMessage = "Name is limited to 32 characters")] public string Name { get; set; } [StringLength(128, ErrorMessage = "Description is limited to 32 characters")] public string Description { get; set; } }
namespace MvcApplication1.Models { /// <summary> /// Note: I am using dynamic objects mainly for efficiency. /// This way I only send back to he client what I really need. /// </summary> public class JsonResponseFactory { public static object ErrorResponse(string error) { return new { Success = false, ErrorMessage = error }; } public static object SuccessResponse() { return new { Success = true }; } public static object SuccessResponse(object referenceObject) { return new { Success = true, Object = referenceObject }; } } }
public static class CarRepository { static List<CarModel> CarList; static CarRepository() { CarList = new List<CarModel>{ new CarModel { Id=1, ImageFileName="FordFocusElectric.jpg", Name="Ford Focus Electric", Description = "Great looking car... plus is green."}, new CarModel { Id=2, ImageFileName="HondaCivic2012.jpg", Name="Honda Civic 2012", Description="You can always count with the Civic"}, new CarModel { Id=3, ImageFileName="HyundaiHCD12.jpg", Name="Hyundai HCD 12", Description="Can't wait for it to come out!"}, new CarModel { Id=4, ImageFileName="ToyotaPriusC.jpg", Name="Toyota Prius C", Description="What does the C stands for?"}}; } /// <summary> /// NOTE: This is for demostration purposes only. /// You would normally have your data access layer, either on the web app or in other libraries. /// </summary> /// <returns></returns> public static List<CarModel> GetCars() { return CarList; } }
*******CONTROLLER:********
public class CarsController : Controller { // // GET: /Cars/ public ActionResult Index() { List<CarModel> model = CarRepository.GetCars(); return View(model); } public ActionResult Edit(int id) { CarModel model = CarRepository.GetCars().Where(c => c.Id == id).FirstOrDefault(); return PartialView(model); } [HttpPost] public JsonResult Edit(CarModel model) { if (ModelState.IsValid) { CarModel car = CarRepository.GetCars().Where(c => c.Id == model.Id).FirstOrDefault(); car.Name = model.Name; car.Description = model.Description; return Json(JsonResponseFactory.SuccessResponse(car), JsonRequestBehavior.DenyGet); } else { return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet); } } }
******* INDEX.CSHTML********
<h2>Index</h2> <div id="commonMessage"></div> <table> @foreach (var item in Model) { <tr> <td> <img src="/content/images/@item.ImageFileName" /> </td> <td> <strong><span class="carName">@item.Name</span></strong><br /> <span class="carDescription">@item.Description</span><br /><br /> @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "editLink" }) // Edit link </td> </tr> } </table> <div id="updateDialog" title="Update Car"></div> //div to show as dialog
<script type="text/javascript"> var linkObj; $(function () { $(".editLink").button(); //Initialize dialog div $('#updateDialog').dialog({ autoOpen: false, width: 400, resizable: false, modal: true, buttons: { "Update": function () { $("#update-message").html(''); //id of the message div in Edit.cshtml and make sure there is nothing on the message before we continue $("#updateCarForm").submit(); // id of the Form in Edit.cshtml }, "Cancel": function () { $(this).dialog("close"); } } }); // Initialization of Dialog div ends $(".editLink").click(function () { //change the title of the dialog and Open it linkObj = $(this); var dialogDiv = $('#updateDialog'); var viewUrl = linkObj.attr('href'); //Get the complete html of the Edit view and fill it in dialogDiv below $.get(viewUrl, function (data) { dialogDiv.html(data); //validation var $form = $("#updateCarForm"); // form id given in Edit View to Open //To make the client side validation work Unbind existing validation and rebind. $form.unbind(); $form.data("validator", null); // Check document for changes $.validator.unobtrusive.parse(document); // Re add validation with changes $form.validate($form.data("unobtrusiveValidation").options); //open dialog dialogDiv.dialog('open'); }); return false; }); }); // updateSuccess called from Ajax.BeginForm in the Edit View. function updateSuccess(data) { if (data.Success == true) { //we update the table's info var parent = linkObj.closest("tr"); parent.find(".carName").html(data.Object.Name); parent.find(".carDescription").html(data.Object.Description); //now we can close the dialog $('#updateDialog').dialog('close'); //twitter type notification $('#commonMessage').html("Update Complete"); $('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400); } else { $("#update-message").html(data.ErrorMessage); $("#update-message").show(); } } </script>
******Edit.cshtml*******
@model MvcApplication1.Models.CarModel @using (Ajax.BeginForm("Edit", "Cars", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess = "updateSuccess" }, new { @id = "updateCarForm" })) { @Html.ValidationSummary(true) <div id="update-message" class="error invisible"></div> <fieldset> <legend>CarModel</legend> @Html.HiddenFor(model => model.Id) <img src="/content/images/@Model.ImageFileName" /> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Description) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div> </fieldset> }
//Ref. Link:
http://ricardocovo.com/2012/04/06/asp-mvc3-editing-records-with-jqueryui-dialogs-and-ajaxforms-razor-version/
0 comments:
Post a Comment