نمایش فرمهای مودال Ajax ایی در ASP.NET MVC به کمک Twitter Bootstrap
نویسنده: وحید نصیری
تاریخ: ۱۳۹۲/۰۳/۲۴ ۸:۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
// <![CDATA[
(function ($) {
$.bootstrapModalAjaxForm = function (options) {
var defaults = {
renderModalPartialViewUrl: null,
renderModalPartialViewData: null,
postUrl: '/',
loginUrl: '/login',
beforePostHandler: null,
completeHandler: null,
errorHandler: null
};
var options = $.extend(defaults, options);
var validateForm = function (form) {
//فعال سازی دستی اعتبار سنجی جیکوئری
var val = form.validate();
val.form();
return val.valid();
};
var enableBootstrapStyleValidation = function () {
$.validator.setDefaults({
highlight: function (element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).addClass(errorClass).removeClass(validClass);
$(element).closest('.control-group').removeClass('success').addClass('error');
}
$(element).trigger('highlited');
},
unhighlight: function (element, errorClass, validClass) {
if (element.type === 'radio') {
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
$(element).removeClass(errorClass).addClass(validClass);
$(element).closest('.control-group').removeClass('error').addClass('success');
}
$(element).trigger('unhighlited');
}
});
}
var enablePostbackValidation = function () {
$('form').each(function () {
$(this).find('div.control-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('error');
}
});
});
}
var processAjaxForm = function (dialog) {
$('form', dialog).submit(function (e) {
e.preventDefault();
if (!validateForm($(this))) {
//اگر فرم اعتبار سنجی نشده، اطلاعات آن ارسال نشود
return false;
}
//در اینجا میتوان مثلا دکمهای را غیرفعال کرد
if (options.beforePostHandler)
options.beforePostHandler();
//اطلاعات نباید کش شوند
$.ajaxSetup({ cache: false });
$.ajax({
url: options.postUrl,
type: "POST",
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#dialogDiv').modal('hide');
if (options.completeHandler)
options.completeHandler();
} else {
$('#dialogContent').html(result);
if (options.errorHandler)
options.errorHandler();
}
}
});
return false;
});
};
var mainContainer = "<div id='dialogDiv' class='modal hide fade in'><div id='dialogContent'></div></div>";
enableBootstrapStyleValidation(); //اعمال نکات خاص بوت استرپ جهت اعتبارسنجی یکپارچه با آن
$.ajaxSetup({ cache: false });
$.ajax({
type: "POST",
url: options.renderModalPartialViewUrl,
data: options.renderModalPartialViewData,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (xhr, status) {
var data = xhr.responseText;
var data = xhr.responseText;
if (xhr.status == 403) {
window.location = options.loginUrl; //در حالت لاگین نبودن شخص اجرا میشود
}
else if (status === 'error' || !data) {
if (options.errorHandler)
options.errorHandler();
}
else {
var dialogContainer = "#dialogDiv";
$(dialogContainer).remove();
$(mainContainer).appendTo('body');
$('#dialogContent').html(data); // دریافت پویای اطلاعات مودال دیالوگ
$.validator.unobtrusive.parse("#dialogContent"); // فعال سازی اعتبارسنجی فرمی که با ایجکس بارگذاری شده
enablePostbackValidation();
// و سپس نمایش آن به صورت مودال
$('#dialogDiv').modal({
backdrop: 'static', //با کلیک کاربر روی صفحه، صفحه مودال بسته نمیشود
keyboard: true
}, 'show');
// تحت نظر قرار دادن این فرم اضافه شده
processAjaxForm('#dialogContent');
}
}
});
};
})(jQuery);
// ]]>using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Mvc4TwitterBootStrapTest.Models
{
public class User
{
public int Id { set; get; }
[DisplayName("نام")]
[Required(ErrorMessage="لطفا نام را تکمیل کنید")]
public string Name { set; get; }
[DisplayName("نام خانوادگی")]
[Required(ErrorMessage = "لطفا نام خانوادگی را تکمیل کنید")]
public string LastName { set; get; }
}
}using System.Web.Mvc;
using Mvc4TwitterBootStrapTest.Models;
namespace Mvc4TwitterBootStrapTest.Controllers
{
public class ModalFormAjaxController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(); //نمایش صفحه اولیه
}
[HttpPost] //برای این حالت امنتر است
//[AjaxOnly]
public ActionResult RenderModalPartialView()
{
//رندر پارشال ویوو صفحه مودال به همراه اطلاعات مورد نیاز آن
return PartialView(viewName: "_ModalPartialView", model: new User { Name = "", LastName = "" });
}
[HttpPost]
//[AjaxOnly]
public ActionResult Index(User user) //ذخیره سازی اطلاعات
{
if (this.ModelState.IsValid)
{
//todo: SaveChanges;
return Json(new { success = true });
}
this.ModelState.AddModelError("", "خطایی رخ داده است");
return PartialView("_ModalPartialView", user);
}
}
}@{
ViewBag.Title = "Index";
var renderModalPartialViewUrl = Url.Action("RenderModalPartialView", "ModalFormAjax");
var postDataUrl = Url.Action("Index", "ModalFormAjax");
}
<h2>
Index</h2>
<a href="#" class="btn btn-primary" id="btnCreate">ثبت اطلاعات</a>
@section JavaScript
{
<script type="text/javascript">
$(function () {
$('#btnCreate').click(function (e) {
e.preventDefault(); //میخواهیم لینک به صورت معمول عمل نکند
$.bootstrapModalAjaxForm({
postUrl: '@postDataUrl',
renderModalPartialViewUrl: '@renderModalPartialViewUrl',
renderModalPartialViewData: {},
loginUrl: '/login',
beforePostHandler: function () {
},
completeHandler: function () {
// Refresh: برای حالتیکه نیاز به به روز رسانی کامل صفحه زیرین باشد
// location.reload();
},
errorHandler: function () {
}
});
});
});
</script>
}@model Mvc4TwitterBootStrapTest.Models.User
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<h5>
افزودن کاربر جدید</h5>
</div>
@using (Html.BeginForm("Index", " ModalFormAjax", FormMethod.Post, new { @class = "modal-form" }))
{
<div class="modal-body">
@Html.ValidationSummary(true, null, new { @class = "alert alert-error alert-block" })
<fieldset class="form-horizontal">
<legend>مشخصات کاربر</legend>
<div class="control-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label" })
<div class="controls">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name, null, new { @class = "help-inline" })
</div>
</div>
<div class="control-group">
@Html.LabelFor(model => model.LastName, new { @class = "control-label" })
<div class="controls">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName, null, new { @class = "help-inline" })
</div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="submit">
ارسال</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">
انصراف</button>
</div>
}body .modal {
width: 560px;
margin-left: -280px;
}$('#dialogDiv').modal({
backdrop: 'static', //با کلیک کاربر روی صفحه، صفحه مودال بسته نمیشود
keyboard: true
}, 'show').css({
'width': '100px',
'max-width': '1000px',
'margin-left': '10px' });publicActionResult Index(User user) //ذخیره سازی اطلاعات
{
if(this.ModelState.IsValid)
{
//todo: SaveChanges;
returnJson(new{ success = true});
}
this.ModelState.AddModelError("", "خطایی رخ داده است");
returnPartialView("_ModalPartialView", user);
} } else {
$('#dialogContent').html(result);
$.validator.unobtrusive.parse("#dialogContent");
enablePostbackValidation();
processAjaxForm('#dialogContent');
if (options.errorHandler)
options.errorHandler();
}public class ProductCategoryViewModel
{
public Product Product{get;set;}
public Category Category{get;set;}
} public ActionResult RenderModalPartialView()
{
//رندر پارشال ویوو صفحه مودال به همراه اطلاعات مورد نیاز آن
return PartialView(viewName: "_ModalPartialView", model: new ProductCategoryViewModel());
} @Html.DropDownListFor(model => model.Product.CategoryId, (SelectList)ViewBag.CategryNames, "--گروه موردنظر را انتخاب کنید--")
if(mvcHost.IsPartialView) {
#>
<# public IEnumerable<SelectListItem> Names { get; set; } model: new ProductCategoryViewModel { Names = ... } <#
if (!mvcHost.IsContentPage) {
#>
<#
}
}
#>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<#= mvcHost.ViewDataType.Name #>
</div>
@using (Html.BeginForm()) {
<div class="modal-body">
@Html.ValidationSummary(true, null, new { @class = "alert alert-error alert-block" })
<fieldset class="form-horizontal">
<legend><#= mvcHost.ViewDataType.Name #></legend>
<#
foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {
if (!property.IsPrimaryKey && !property.IsReadOnly && property.Scaffold) {
#>
<div class="control-group">
<#
if (property.IsForeignKey) {
#>
@Html.LabelFor(model => model.<#= property.Name #>, "<#= property.AssociationName #>",new {@class="control-label"})
<#
} else {
#>
@Html.LabelFor(model => model.<#= property.Name #>,new {@class="control-label"})
<#
}
#>
<div class="controls">
<#
if (property.IsForeignKey) {
#>
@Html.DropDownList("<#= property.Name #>", String.Empty)
<#
} else {
#>
@Html.EditorFor(model => model.<#= property.Name #>)
<#
}
#>
@Html.ValidationMessageFor(model => model.<#= property.Name #>,null,new{@class="help-inline"})
</div>
</div>
<#
}
}
#>
</fieldset>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="submit">
ارسال</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">
انصراف</button>
</div>
} return Json(new { success = true }); if (result.success) {
$('#dialogDiv').modal('hide');
if (options.completeHandler)
options.completeHandler(); @(Html.Kendo().ComboBoxFor(model => model.ParentId)
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { style = "width:150px" })
.Filter("contains")
.AutoBind(false)
.MinLength(3)
.Placeholder(CategoryResource.Category)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetAllGroups", "Utility");
})
.ServerFiltering(false);
})
) return Json( "test");
completeHandler: function (data) {
alert(data)
} return Json(
new
{
success = true,
message = Resources.Global.Texts.Successful
}); completeHandler: function (data) {
alert(data.success)
} success: function (result) {
if (result.success) {
$('#dialogDiv').modal('hide');
if (options.completeHandler)
options.completeHandler(); | 1 | return Json( new { success = true }); |
| 1 2 3 4 | if (result.success) { $( '#dialogDiv' ).modal( 'hide' ); if (options.completeHandler) options.completeHandler(); |
$.ajax({
type: "POST",
url: options.renderModalPartialViewUrl,
data: options.renderModalPartialViewData, $.bootstrapModalAjaxForm({
postUrl: '@postDataUrl',
renderModalPartialViewUrl: '@renderModalPartialViewUrl',
renderModalPartialViewData: { id: 1}, public ActionResult RenderModalPartialView(int id)
{
//رندر پارشال ویوو صفحه مودال به همراه اطلاعات مورد نیاز آن
return PartialView(viewName: "_ModalPartialView", model: new User { Name = "", LastName = "" });
}
renderModalPartialViewData: JSON.stringify({ id: 1 }), function LoadCt() {
$('#myModal').modal('hide');
$.ajax({
type: "POST",
url: "/CONTROLLER/ACTIONMETHOD",
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "html",
complete: function (xhr, status) {
var data = xhr.responseText;
$('cats').html(data);
}
});
} public ActionResult ACTIONMETHOD()
{
var model = stuff from _db;
return PartialView("_Get", model);
} function test() {
$.ajax({
url: "/CONTROLLER/ACTIONMETHOD",
type: "GET"
})
.done(function (partialViewResult) {
$("#cats").html(partialViewResult);
});
}