در این مقاله میخواهیم راجب نحوه ی ایجاد فرم Ajax در MVC صحبت کنیم.میخواهیم به نحوه ی اجرای تابعیت Ajax در ثبت فرم با استفاده از JavaScript بپردازیم. این یک روش تمرینی است ، پس ما یک مثال برای افزودن کاربر و نمایش در لیست ایجاد میکنیم.
فرم افزودن کاربر با استفاده از JavaScript ثبت میشود.
در این مقاله علاوه بر تمام کد های مورد نیاز سورس نیز برای دانلود قرار داده شده است. امیدوارم از آن استفاده کنید. با من در این مقاله ی جالب همراه باشید …
Ajax در MVC
زمانی که یک فرم ثبت میشود از یک درخواست POST استفاده کنید سپس یک response در فرمت JSON بازمیگرداند.
به همین دلیل ما یک کلاس معمول ایجاد میکنیم تا همه ی POST های فرم هایمان دارای ساختار داده ای یکسانی در response باشند.
قطعه کد زیر مربوط به کلاس ResponseDate میباشد :
namespace AjaxForm.Serialization { public class ResponseData { public T Data { get; set; } public string RedirectUrl { get; set; } public bool IsSuccess { get { return this.Data == null; } } } }
از آنجایی که ما احتیاج به بازگرداندن داده در فرمت JSON داریم ، متد های action یک JsonResult بازمیگرداند.
ما “Newtonsoft.Json.5.0.8” با استفاده از بسته های NuGet نصب میکنیم و کلاسی اختصاصی که از JsonResult ارث بری کند ، مینویسیم.
قطعه کد زیر مربوط به کلاس JsonResult میباشد:
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.IO; using System.Web; using System.Web.Mvc; namespace AjaxForm.Serialization { public class JsonNetResult : JsonResult { public JsonNetResult() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Error, ContractResolver = new CamelCasePropertyNamesContractResolver() }; } public JsonSerializerSettings Settings { get; private set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("JSON GET is not allowed"); } HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data == null) { return; } var scriptSerializer = JsonSerializer.Create(this.Settings); using (var sw = new StringWriter()) { scriptSerializer.Serialize(sw, this.Data); response.Write(sw.ToString()); } } } }
حال ما کار های موردنیاز برای سریالی کردن نتیجه را انجام داده ایم.
از این پس یک BasController که دارای متد های لازم برای نتایج JSON و model خطا است ، ایجاد میکنیم.
همانند قطعه کد زیر:
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.IO; using System.Web; using System.Web.Mvc; namespace AjaxForm.Serialization { public class JsonNetResult : JsonResult { public JsonNetResult() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Error, ContractResolver = new CamelCasePropertyNamesContractResolver() }; } public JsonSerializerSettings Settings { get; private set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("JSON GET is not allowed"); } HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data == null) { return; } var scriptSerializer = JsonSerializer.Create(this.Settings); using (var sw = new StringWriter()) { scriptSerializer.Serialize(sw, this.Data); response.Write(sw.ToString()); } } } }
اجرای فرم Ajax بر روی رابط کاربری
برای اجرای فرم Ajax ما یک فضای نام JavaScript ایجاد میکنیم که در آن یک کلاس JavaScript برای درخواست POST در فرم مشخص میکنیم.
این کلاس چک میکند که آیا فرم در قسمت ثبت معتبر است یا خیر.
اگر معتبر بود ، آن را ثبت میکند ، در غیر این صورت یک پیغام خطا نمایش داده خواهد شد.
همچنین میتوانید یک متد callback همانند onSuccess برای راه اندازی کلاس نیز مشخص کنید.
قطعه کد زیر برای فضای نام Global است:
var Global = {}; Global.FormHelper = function (formElement, options, onSucccess, onError) { var settings = {}; settings = $.extend({}, settings, options); formElement.validate(settings.validateSettings); formElement.submit(function (e) { if (formElement.valid()) { $.ajax(formElement.attr("action"), { type: "POST", data: formElement.serializeArray(), success: function (result) { if (onSucccess === null || onSucccess === undefined) { if (result.isSuccess) { window.location.href = result.redirectUrl; } else { if (settings.updateTargetId) { $("#" + settings.updateTargetId).html(result.data); } } } else { onSucccess(result); } }, error: function (jqXHR, status, error) { if (onError !== null onError !== undefined) { onError(jqXHR, status, error); $("#" + settings.updateTargetId).html(error); } }, complete: function () { } }); } e.preventDefault(); }); return formElement; };
حال ما یک کنترلر برای رابط کاربری ایجاد میکنیم که درخواست های GET/POST را برای افزودن کاربر و نمایش لیست کاربران کنترل کند.
قطعه کد زیر برای UserController است :
using AjaxForm.Models; using AjaxForm.Serialization; using System.Collections.Generic; using System.Web.Mvc; namespace AjaxForm.Controllers { public class UserController : BaseController { public static ListUserViewModel users = new ListUserViewModel(); public ActionResult Index() { return View(users); } [HttpGet] public ActionResult AddUser() { UserViewModel model = new UserViewModel(); return View(model); } [HttpPost] public ActionResult AddUser(UserViewModel model) { if (ModelState.IsValid) { users.Add(model); return NewtonSoftJsonResult(new ResponseDatastring { RedirectUrl = @Url.Action("Index", "User") }); } return CreateModelStateErrors(); } } }
حال یک view ایجاد میکنیم که لیست افزودن کاربر را نشان میدهد و توسط Index action آن را رندر میشود.
قطعه کد زیر نیز برای قسمت برای قسمت Index view میباشد.
@model ListAjaxForm.Models.UserViewModel div class="panel panel-primary" div class="panel-heading panel-head"User List/div div class="panel-body" div class="btn-group" a id="addUser" href="@Url.Action("AddUser")" class="btn btn-primary" i class="fa fa-plus"/i Add User /a /div table class="table table-striped" thead tr thUserName/th thEmail/th /tr /thead tbody @foreach (var item in Model) { tr td@item.UserName/td td@item.Email/td /tr } /tbody /table /div /div </pre> سپس یک view برای AddUser همانند زیر ایجاد میکنیم : <pre class="lang:xhtml decode:true ">@model AjaxForm.Models.UserViewModel div class="panel panel-primary" div class="panel-heading panel-head"Add User/div div id="frm-add-user" class="panel-body" @using (Html.BeginForm()) { div id="validation-summary"/div div class="form-horizontal" div class="form-group" @Html.LabelFor(model = model.UserName, new { @class = "col-lg-2 control-label" }) div class="col-lg-9" @Html.TextBoxFor(model = model.UserName, new { @class = "form-control" }) @Html.ValidationMessageFor(model = model.UserName) /div /div div class="form-group" @Html.LabelFor(model = model.Email, new { @class = "col-lg-2 control-label" }) div class="col-lg-9" @Html.TextBoxFor(model = model.Email, new { @class = "form-control" }) @Html.ValidationMessageFor(model = model.Email) /div /div div class="form-group" div class="col-lg-9"/div div class="col-lg-3" button class="btn btn-success" id="btnSubmit" type="submit" Submit /button /div /div /div } /div /div @section scripts { @Scripts.Render("~/bundles/jqueryval","~/Scripts/global.js","~/Scripts/user_add_user.js") } اکنون یک JavaScript ایجاد میکنیم (user_add_user.js) که راه اندازی ثبت فرم را با استفاده از درخواست POST انجام میدهد. میتوانیم متد های callback اضافی یا همچنین تنظیمات معتبرسازی اضافی را به آن پاس دهیم. در زیر قطعه کد آن آورده شده است : <pre class="lang:js decode:true">(function ($) { function AddUser(){ var $this = this; function initilizeUser() { var formAddUser = new Global.FormHelper($("#frm-add-user form"), { updateTargetId: "validation-summary" }) } $this.init = function () { initilizeUser(); } } $(function () { var self = new AddUser(); self.init(); }) }(jQuery))
اکنون برنامه را اجرا کنید ، صفحه ی اولیه نشان دهنده ی لیست کاربران به همراه دکمه ای برای افزودن کاربر است.
حال بر روی دکمه ی افزودن کلیک کنید و صفحه ای همانند زیر خواهیم داشت :
حال بر روی دکمه ی ثبت کلیک کنید تا نتیجه را ببینید.
هیچ دیدگاهی نوشته نشده است.