ASP.NET MVC下Ajax.BeginForm方式無刷新提交表單實(shí)例
有時(shí)候,不得不考慮到以下場景問題:
數(shù)據(jù)庫表字段會(huì)頻繁更改擴(kuò)展,而流行的重業(yè)務(wù)的js框架過于依賴json數(shù)據(jù)接口,導(dǎo)致的問題是,數(shù)據(jù)庫表更改 -> 數(shù)據(jù)接口更改 -> 前段框架邏輯更改。。。
一不小心就陷入坑坑洼洼。
這樣的話,原來純ASP.NET MVC綁定的方式,還是可以一用的,因?yàn)樵摲绞讲挥迷贋槟敲炊鄇s代碼煩惱。
不好意思,前面自說自話啊,直接上干貨代碼了————
Ajax.BeginForm
@{
Layout = null;
var ajaxOptions = new AjaxOptions {
UpdateTargetId = "updateHolder",
OnBegin = "DeliverableEdit.onBegin",
OnFailure = "DeliverableEdit.onFailure",
OnSuccess = "DeliverableEdit.onSuccess",
OnComplete = "DeliverableEdit.onComplete",
HttpMethod = "Post"
};
}
@using ( Ajax.BeginForm("Save", "DesignDeliverable", null, ajaxOptions, new { @class = "form-horizontal", id = "editForm" }) ) {
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.TaskCode)
@Html.HiddenFor(x => x.ShortName)
<div class="container-fluid pad-15">
<div class="row">
<div class="col-xs-6">
<div id="updateHolder" style="display:none;"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Title</label>
<div class="col-sm-4">
@Html.TextBoxFor(x => x.Name, new { @class = "form-control", placeholder = "Title" })
@Html.ValidationMessageFor(x => x.Name)
</div>
<label class="col-sm-2 control-label">Type</label>
<div class="col-sm-4">
@Html.DropDownListFor(x => x.DeliverableType,
new List<SelectListItem> {
new SelectListItem { Text = "Type 1", Value = "1" },
new SelectListItem { Text = "Type 2", Value = "2" },
new SelectListItem { Text = "Type 3", Value = "3" },
new SelectListItem { Text = "Type 4", Value = "4" },
new SelectListItem { Text = "Type 5", Value = "5" },
},
new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
@Html.TextAreaFor(x => x.Description, new { @class = "form-control", rows = 4 })
</div>
</div>
<div class="form-group" style="margin-bottom: 3px;">
<div class="col-sm-2 col-sm-offset-10">
Weight
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Phase</label>
<div class="col-sm-3">
@Html.DropDownListFor(x => x.Phase,
new List<SelectListItem> {
new SelectListItem { Text = "Phase 1", Value = "1" },
new SelectListItem { Text = "Phase 2", Value = "2" },
new SelectListItem { Text = "Phase 3", Value = "3" },
new SelectListItem { Text = "Phase 4", Value = "4" },
new SelectListItem { Text = "Phase 5", Value = "5" },
},
new { @class = "form-control" })
</div>
<label class="col-sm-2 control-label">First</label>
<div class="col-sm-3">
<input class="form-control" type="text" placeholder="" />
</div>
<div class="col-sm-2">
<input class="form-control" type="text" placeholder="Weight" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Detail</label>
<div class="col-sm-3">
@Html.TextBoxFor(x => x.Detail, new { @class = "form-control", placeholder = "Detail" })
@Html.ValidationMessageFor(x => x.Detail)
</div>
<label class="col-sm-2 control-label">Second</label>
<div class="col-sm-3">
<input class="form-control" type="text" placeholder="" />
</div>
<div class="col-sm-2">
<input class="form-control" type="text" placeholder="Weight" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Size</label>
<div class="col-sm-3">
@Html.TextBoxFor(x => x.Size, new { @class = "form-control", placeholder = "Size" })
</div>
<label class="col-sm-2 control-label">Third</label>
<div class="col-sm-3">
<input class="form-control" type="text" placeholder="" />
</div>
<div class="col-sm-2">
<input class="form-control" type="text" placeholder="Weight" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">WBS Code</label>
<div class="col-sm-3">
@Html.TextBoxFor(x => x.WbsNumber, new { @class = "form-control", placeholder = "WBS Code" })
</div>
<label class="col-sm-2 control-label">Fourth</label>
<div class="col-sm-3">
<input class="form-control" type="text" placeholder="" />
</div>
<div class="col-sm-2">
<input class="form-control" type="text" placeholder="Weight" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Room</label>
<div class="col-sm-3">
@Html.DropDownListFor(x => x.RoomId,
(ViewBag.Rooms as List<SelectListItem>),
new { @class = "form-control" })
</div>
<label class="col-sm-2 control-label">A Variance</label>
<div class="col-sm-3">
<input class="form-control" type="text" placeholder="A Variance" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Area</label>
<div class="col-sm-3">
@Html.DropDownListFor(x => x.AreaId,
(ViewBag.Areas as List<SelectListItem>),
new { @class = "form-control" })
</div>
<label class="col-sm-2 control-label">B Variance</label>
<div class="col-sm-3">
<input class="form-control" type="text" placeholder="B Variance" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Comments</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4"></textarea>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<div class="col-sm-12">
<label class="control-label">Documents</label>
<table class="table table-bordered table-hover table-condensed mt-10">
<thead>
<tr>
<th>File Name</th>
<th>Revision</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>P-001.pdf</td>
<td>01</td>
<td>03/15/2017</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="page_footer absolute-position">
<div class="page_footer_inner page_footer_light text-right">
@if ( Request["action"] != "View" ) {
<button class="btn btn-primary" id="btnSave"><i class="fa fa-floppy-o fa-fw"></i> Save</button>
}
<button id="btnCancel" class="btn btn-default"><i class="fa fa-close fa-fw"></i> Close</button>
</div>
<span id="notification"></span>
</div>
}
<script type="text/javascript">
var DeliverableEdit = DeliverableEdit || {};
(function (o) {
o.timer = null;
o.displayLoading = function (target) {
var element = $(target);
kendo.ui.progress(element, true);
o.timer = setTimeout(function () {
kendo.ui.progress(element, false);
}, 50);
};
o.hideLoading = function (target) {
setTimeout(function () {
clearTimeout(o.timer);
}, 50);
};
o.initializeValidation = function () {
$.validator.setDefaults({
showErrors: function (errorMap, errorList) {
$(".page_footer_inner button").removeProp("disabled", "disabled");
// Clean up any tooltips for valid elements
$.each(this.validElements(), function (index, element) {
var $element = $(element);
$element.data("title", "") // Clear the title - there is no error associated anymore
.removeClass("field-validation-error")
.tooltip("destroy");
});
// Create new tooltips for invalid elements
$.each(errorList, function (index, error) {
var $element = $(error.element);
$element.tooltip("destroy") // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
.data("title", error.message)
.data("placement", "bottom")
.addClass("field-validation-error")
.tooltip(); // Create a new tooltip based on the error messsage we just set in the title
});
}
});
$.validator.unobtrusive.parse($("#editForm"));
};
o.showSuccess = function (msg) {
$("#notification").data('kendoNotification').show(msg, "success");
};
o.showWarning = function (msg) {
$("#notification").data('kendoNotification').show(msg, "warning");
};
// Events during the submit of Ajax.Form
o.onBegin = function () {
$(".page_footer_inner button").prop("disabled", "disabled");
o.displayLoading($(".form-horizontal"));
}
o.onSuccess = function (data) {
o.hideLoading(o.timer);
if (!data || !data.code) {
o.showWarning("Failure,please try it again.");
return;
}
if (data && data.code) {
gridView.refreshGrid();
o.showSuccess("Saved successfully.");
setTimeout(function () {
gridView.closeDeliverableDialog();
}, 500);
}
}
o.onFailure = function (request, error) {
o.hideLoading(o.timer);
o.showWarning("Failure,please try it again.");
}
o.onComplete = function (request, status) {
o.hideLoading(o.timer);
$(".page_footer_inner button").removeProp("disabled", "disabled");
}
})(DeliverableEdit);
$(function () {
// To fix jquery.validation invalid issue
DeliverableEdit.initializeValidation();
$("#btnCancel").click(function (e) {
e.preventDefault();
gridView.closeDeliverableDialog();
});
$("#btnSave").click(function (e) {
e.preventDefault();
$(".form-horizontal").submit();
$(".page_footer_inner button").prop("disabled", "disabled");
});
$("#notification").kendoNotification({
position: {
pinned: true,
top: 15,
left: '50%'
},
autoHideAfter: 1000
});
});
</script>
記得引用對應(yīng)的js庫————
<link href="~/content/libs/bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet" type="text/css" /> <link href="~/content/libs/fa/css/font-awesome.min.css" rel="external nofollow" rel="stylesheet" type="text/css" /> <link href="~/content/app/css/site.css" rel="external nofollow" rel="stylesheet" type="text/css" /> <link href="~/content/app/css/bootstrap-extend.css" rel="external nofollow" rel="stylesheet" type="text/css" /> <link href="~/content/app/css/bootstrap-override.css" rel="external nofollow" rel="stylesheet" type="text/css" /> <script src="~/content/libs/jquery/jquery.min.js"></script> <script src="~/content/libs/jquery/jquery.validate-vsdoc.js"></script> <script src="~/content/libs/jquery/jquery.validate.js"></script> <script src="~/content/libs/jquery/jquery.validate.unobtrusive.js"></script> <script src="~/Content/libs/jquery/jquery.unobtrusive-ajax.min.js"></script>
后端代碼————
[Route("~/DesignDeliverable/Edit/{id?}")]
[HttpGet]
public ActionResult Edit(Guid? id) {
using ( EmpsDbContext db = new EmpsDbContext() ) {
DesignDeliverable entity = null;
if ( id.HasValue ) {
entity = db.DesignDeliverables.SingleOrDefault(x => x.Id == id.Value);
}
else {
entity = new DesignDeliverable();
}
ViewBag.Rooms = RoomFacade.GetAll().Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
ViewBag.Areas = AreaFacade.GetAll().Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
return View(entity);
}
}
[Route("~/DesignDeliverable/Save")]
[HttpPost]
public JsonResult Edit(DesignDeliverable model) {
using ( EmpsDbContext db = new EmpsDbContext() ) {
if ( !ModelState.IsValid ) {
return Error();
}
try {
model.GroupId = new Guid("e030c300-849c-4def-807e-a5b35cf144a8"); //todo: fix this hardcode
db.DesignDeliverables.AddOrUpdate(model);
db.SaveChanges();
return Success();
}
catch {
//TODO: to store the exception message
}
return Error();
}
}
以上這篇ASP.NET MVC下Ajax.BeginForm方式無刷新提交表單實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- .net core利用orm如何操作mysql數(shù)據(jù)庫詳解
- .net MVC使用IPrincipal進(jìn)行Form登錄即權(quán)限驗(yàn)證(3)
- .net WINFORM的GDI雙緩沖的實(shí)現(xiàn)方法
- Asp.net webForm設(shè)置允許表單提交Html的方法
- Asp.net mvc驗(yàn)證用戶登錄之Forms實(shí)現(xiàn)詳解
- asp.net mvc中Forms身份驗(yàn)證身份驗(yàn)證流程
- asp.net core標(biāo)簽助手的高級用法TagHelper+Form
- 深入理解Asp.Net中WebForm的生命周期
- .net MVC中使用forms驗(yàn)證詳解
- .NET Orm性能測試分析
相關(guān)文章
ASP.NET Core使用JWT認(rèn)證授權(quán)的方法
這篇文章主要介紹了ASP.NET Core使用JWT認(rèn)證授權(quán)的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
.NET中l(wèi)ambda表達(dá)式合并問題及解決方法
這篇文章主要介紹了.net?lambda表達(dá)式合并問題,解決方法是自己構(gòu)造一個(gè)新的表達(dá)式,構(gòu)造表達(dá)式需要用到expression類,本文結(jié)合實(shí)例代碼給大家詳細(xì)介紹,需要的朋友可以參考下2022-10-10
用戶控件(ASCX)向網(wǎng)頁(ASPX)傳值使用反射實(shí)現(xiàn)
用戶控件向網(wǎng)頁傳遞值,網(wǎng)上的方法有很多,本文嘗試一下使用反射來實(shí)現(xiàn),感興趣的朋友可以參考下哈,希望可以幫助到你2013-03-03
ASP.Net中利用CSS實(shí)現(xiàn)多界面的兩種方法
這篇文章主要介紹了ASP.Net中利用CSS實(shí)現(xiàn)多界面的兩種方法,包括動(dòng)態(tài)加載css樣式與動(dòng)態(tài)設(shè)置頁面同類控件的方法來實(shí)現(xiàn)該功能,是非常具有實(shí)用價(jià)值的技巧,需要的朋友可以參考下2014-12-12
.Net Core使用OpenXML導(dǎo)出、導(dǎo)入Excel
這篇文章主要為大家詳細(xì)介紹了.Net Core使用OpenXML導(dǎo)出、導(dǎo)入Excel的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
ASP.NET MVC小結(jié)之基礎(chǔ)篇(一)
本文是ASP.NET MVC系列的第一篇文章,跟其他學(xué)習(xí)系列一樣,咱們先來點(diǎn)基礎(chǔ)知識(shí),之后再循序漸進(jìn)。我們先從asp.net mvc的概念開始吧。2014-11-11

