大佬教程收集整理的这篇文章主要介绍了Ajax.BeginForm()知多少,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在ASP.NET MVC中,Ajax.beginForm扮演着异步提交的重要角色。其中就有五个重载方法,但是在实际应用中,你未必使用的得心应手,今天我们就从主要的参数来一探究竟。s.jianshu.io/upload_images/2799767-029d3a894fe5a11f.png?imageMogr2/auto-orient/Strip%7CimageView2/2/w/1240" alt="重载方法">
用于指定请求地址的Action名称。
用于指定请求地址的Controller名称。
用来传递参数,支持两种数据类型(两种传参方式):
new { id = 1,type = 1 }
new RouteValueDictionary{ {"id",1},{"type",1} }
用于指定生成form表单的html属性。也支持两种赋值方式:
new{id = "frm",@class = "cls" }
由于class是C#中的关键字,因此需要在前面加@符号Dictionary htmlAttr = new Dictionary
{
{"id","frm"},{"class","cls"}
};
生成的代码:
s.jianshu.io/upload_images/2799767-751707f50d416d0d.png?imageMogr2/auto-orient/Strip%7CimageView2/2/w/1240" alt="ajaxOptions 参数列表">
看到这么多的参数,是不是一脸懵逼,且听我一一讲解。
new AjaxOption(){Confirm:"确认提交?"}
new AjaxOption(){httpR_586_11845@ethod = "GET"}
@using (Html.beginFrom( new AjaxOptions(){Url= '/Tasks/Create'})){ }
下面我将具体讲解第5和第8个的具体用法。
div#loading { display: none; }
- 在form中指定LoadingElementId
@using (Ajax.beginForm(MVC.Account.Login(),new AjaxOptions {
Onsuccess = "onLoginsuccess",LoadingElementId = "loading",OnBegin = "onLoginBegin" },new { @id = "loginForm" })){ }
- 定义js函数,隐藏加载动画。
但其实这几个js方法大家未必用得好。先来看看常规用法,其中指定的js函数均未传参。
@using (Ajax.beginForm("Create","Tasks",new AjaxOptions()
{
updateTargetId = "taskList",OnBegin = "onBegin",Onsuccess = "onsuccess",OnFailure = "onFailure",OnComplete = "onComplete"
}))
{
}
//Js函数
function onsuccess() {
alert('success!');
}
如果我想当请求失败时,弹出返回的错误提示并清空form表单怎么办呢?
@using (Ajax.beginForm("Create",OnFailure = "onFailure("#formid")",}))
{
}
//Js函数
function onFailure(id) {
alert("Somthing is wrong!"); //alert弹出错误提示信息。
var $form = $(id);
$form.reset();//清空form表单。
}
这样实现并没有拿到返回的错误数据,那到底如何传参呢?
经过参考,终于弄清,默认的传参是怎样的。
OnBegin – xhrOnComplete – xhr,statusOnSuccess – data,status,xhrOnFailure – xhr,error
也就是说,默认未指定参数的js函数实际等同于:
@using (Ajax.BeginForm("Create",OnBegin = "onBegin(xhr)",OnSuccess = "onSuccess(data,xhr)",OnFailure = "onFailure(xhr,error)",OnComplete = "onComplete(xhr,status)"
}))
{
}
看到这里,我们再来看看上例【如果我想当请求失败时,弹出返回的错误提示并清空form表单怎么办呢?】
@using (Ajax.BeginForm("Create",error,"#formid")",}))
{
}
//Js函数
function onFailure(xhr,id) {
alert(error); //alert弹出错误提示信息。
var $form = $(id);
$form.reset();//清空form表单。
}
通过默认的参数,成功拿到错误信息,并且可传递自定义参数。
读到这里,觉得不错,就给个推荐吧!
大佬总结
以上是大佬教程为你收集整理的Ajax.BeginForm()知多少全部内容,希望文章能够帮你解决Ajax.BeginForm()知多少所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。