asp.net-mvc – asp.net mvc 3 – ajax表单提交和验证
|
我很抱歉,如果这已经被问到,但我一直在寻找一段时间,但我发现所有的都是相当老的帖子(mvc1,mvc2)。
This看起来像是可以工作,但不包括服务器端验证。 1)我不确定是否应该使用AjaxHelper.BeginForm或使用raw jquery调用($ .ajax)?这里推荐的方法是什么? 2)如何处理客户端和服务器端验证?我希望mvc框架提供一个内置的机制来处理这个问题? 我正在使用asp.net mvc3 / razor与unobtrussive JavaScript验证。 谢谢! 编辑:(根据Bobby B的要求)。 这是我使用的JavaScript代码: <script type="text/javascript">
function ajaxValidate() {
return $('form').validate().form();
}
function getGbPostSuccess(ajaxContext){
// .... it is not necessary to do anything here.
}
function showFaliure(ajaxContext){
// handle failure
}
HTML片段: @using (Ajax.BeginForm("Index","Home",new AjaxOptions
{
UpdateTargetId = "form1",InsertionMode = InsertionMode.Replace,OnBegin = "ajaxValidate",OnSuccess = "getGbPostSuccess",OnFailure = "showFaliure"
}))
{
解决方法为此,我一直在使用 malsup’s jQuery form plugin。我老实说不熟悉AjaxHelper,但是看起来会像你想要的那样做。只要进行客户端和服务器端验证,只要您使用模型绑定和System.DataAnnotations命名空间中的属性,这些都将自动发生。public class MyModel
{
[Required(ErrorMessage = "Please enter your name")]
public String Name { get; set; }
[Required(ErrorMessage = "Please enter your email")]
public String Email { get; set; }
[Required(ErrorMessage = "Please enter a rating")]
[Range(1,5,ErrorMessage = "The rating must be between 1 and 5")]
public Int32 Rating { get; set; }
}
[HttpPost]
public ActionResult Index(MyModel myModel)
{
if(ModelState.IsValid)
{
// good to go,put it in the DB or whatever you need to do
}
else
{
return View(model); // return the user back to the page,ModelState errors can be viewed using Html.ValidationSummary() or individual Html.ValidationMessageFor() calls
}
}
如果您正在进行自己的自定义服务器端验证,您可以通过创建实现ValidationAttribute的属性来创建自己的自定义验证属性,或者通过调用ModelState.Errors.Add()(或其周围的某些东西)添加验证错误,我没有参考资料) 对于客户端,MVC将根据您的模型上的DataAnnotations属性为您生成客户端验证。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – ASP.NET MVC – Partial View可以有一个控制
- asp.net-mvc – ELMAH MVC 2 – Castle Windsor的问题
- asp.net-mvc – Uploadify(会话和身份验证)与ASP.NET MVC
- asp.net-mvc – ASP.NET MVC:确保用户始终拥有会话变量集
- ASP.Net会话超时检测:Session.IsNewSession和SessionCooki
- asp.net – 如何使用Fiddler编辑HTTP请求
- asp.net html控件的File控件实现多文件上传实例分享
- ASP.NET MVC表单和双字段
- asp.net – MVC 4数据注释“显示”属性
- asp.net阻止表单提交两次
- asp.net-mvc – Web API和ASP MVC之间的主要区别
- asp.net – 用于Active Directory帐户的Oauth 2令
- .net – 只有在配置中enableSessionState设置为t
- asp.net – 在资源文件中存储SQL查询是不好的做法
- asp.net-mvc-routing – @ Url.Action获取?附加
- asp.net-web-api2 – 如何在WebAPI中使用Swagger
- asp.net – 您是否将助手类存储在单独的程序集中
- asp.net-core – Razor模板中的特殊字符未正确编
- asp.net-mvc – 在asp.net MVC中使用的TempData集
- asp.net – 用户控制验证组问题
