asp.net-mvc – asp.net mvc 3 – ajax表单提交和验证
我很抱歉,如果这已经被问到,但我一直在寻找一段时间,但我发现所有的都是相当老的帖子(mvc1,mvc2)。
我有一个表单,我想通过Ajax提交。 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 – 当用户使表单失效时,如何点击取消按钮时,如何清
- asp.net – 需要一个Web表单示例编辑带子项的父实体对象
- asp.net-mvc – MVC 4,复选框列表和我
- asp.net – 使用ITemplate对自定义控件进行数据绑定
- 使用asp.net FtpWebRequest 实现FTP常用功能
- ASP.NET中操作SQL数据库(连接字符串的配置及获取)
- ASP.NET Health Monitoring和ELMAH是否相互替代?
- asp.net-mvc – 将Linq2Sql对象传递给Views有什么问题?
- asp.net-mvc-4 – 具有动态部分视图创建的MVC Ajax
- asp.net – 处理包含页面的用户控制事件