ajax - mvc3 - ajax表单提交和服务器端验证

标签 ajax asp.net-mvc-3 jquery asp.net-ajax

我确信已经有人问过这个问题,但我一直在尝试给出的所有解决方案,但给定的解决方案都不能解决我的问题。可能是我没有正确实现。

我正在使用 MVC3、razor、jQuery。

我有一个新用户注册表。注册成功后,我想在对话框中显示成功消息(注册类型不同)。

如果 ModelState 有任何错误,则意味着 ModelState.IsValid == false,我想在 ValidationSummary 中显示错误。

查看

function OnBegin () { alert('begin'); return $('form').validate().form(); }
function OnSuccess () { alert('success'); DisplaySucess()}
function OnFailure () { alert('failure'); }
function DisplaySuccess() {
    var typeOfRegistration = $('input:radio[name=RegistrationType]:checked').val();
    var msg;
    if (typeOfRegistration == 0) {
        msg = "You are successfully enrolled for Algebra classes.";
    }
    if (typeOfRegistration == 1) {
        msg = "You are registered with your email address. Someone would contact you with an email.";
    }
    if (typeOfRegistration == 2) {
        msg = "Thank you for filling up this form. One welcome packet would be delivered with in next 15 days";
    }

    msg = msg.replace(/\n/g, '<br />');
    $('#dialog').html(msg);
    $('#dialog').dialog('open');
}
@model Models.RegistrationModel
@using (Ajax.BeginForm("NewRegistration", "Account", new AjaxOptions() { OnBegin="OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{ 
  @Html.ValidationSummary()
    <div>
    Register<br />
    @Html.RadioButton("RegistrationType ", "0", true) New Algebra class<br />
    @Html.RadioButton("RegistrationType ", "1") New user registration by email<br />
    @Html.RadioButton("RegistrationType ", "2") New user registration by mailing address<br/>
   ..some more types
</div>
<div>
    …here I display/hide controls based on Registration type selected.
        <div>
    @Html.LabelFor("UserName")
    @Html.TextBox("UserName")</div>
}

Controller

public ActionResult NewRegistration(RegistrationModel model)
{

         if (Request.IsAjaxRequest())
         {
             if (!ModelState.IsValid) { 
        //Ques: How do I display this in ValidationSummary. 
        return Json(new object[] { false, "Contains Email Address", ModelState.GetAllErrors() }); 
        }
             else { 
        if (UserNameIsTaken){ 
            //Ques: This does not show in ValidationSummary
            ModelState.AddModelError("_FORM", "This username is already taken. Please pick a different username.");
        }
       }
    }
         else if (!ModelState.IsValid) { return View(model); }

}

型号

public class RegistrationModel: IValidatableObject
{
[Required] //this gets displayed in ValidationSummary as Client-side validation
    public string UserName { get; set; }
    .. and all fields here
}
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
        if (!string.IsNullOrEmpty(UserName) && UserName.Contains(EmailAddress)) {
            yield return new ValidationResult("Username cannot contain email address", new[] { "UserName" });
        }
    }

Web.config 有

UnobtrusiveJavaScriptEnabled="true" and ClientValidationEnabled="true"

包含的 .js 文件是

script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript">

script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">

script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript">

script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript">

我在这里缺少什么?还有其他选择吗? 提前致谢。

最佳答案

我认为通过 ajax 发布表单只会出现客户端错误。

服务器端错误,需要通过 Json 返回,然后通过 jQuery 或纯 JavaScript“插入”到标记中。

Here you can see and download a fully working example.

关于ajax - mvc3 - ajax表单提交和服务器端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8827706/

相关文章:

javascript - Window.onbeforeunload - 了解用户点击了什么 Angular 5

jquery - JSON数据打印在HTML中的(element).html中

javascript - 如何使用 ActiveMQ ajax 向特定选择器发送消息

ajax - CORS 和 Azure 存储 (PHP)

javascript - 禁用调试时,使用捆绑缩小的脚本在 ASP.NET MVC 3 中不起作用

c# - ASP MVC 3 - 来自 ViewModel 的图表

asp.net-mvc-3 - .NET 4.0 MEF。可插入的 ASP.NET MVC 3.0 方法

javascript - Google Charts - 从 Ajax 创建数据

jquery - 在 chrome 上带有粘性标题的 html5 背景视频

javascript - 更改 CSS :before if and ID has a specific class