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

时间:2012-01-11 22:33:17

标签: 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>
}

控制器

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”和ClientValidationEnabled =“true”

包含的.js文件是

  

script src =“@ Url.Content(”〜/ Scripts / jquery-1.7.1.min.js“)”type =“text / javascript”&gt;

     

script src =“@ Url.Content(”〜/ Scripts / jquery.validate.min.js“)”type =“text / javascript”&gt;

     

script src =“@ Url.Content(”〜/ Scripts / jquery.validate.unobtrusive.min.js“)”type =“text / javascript”&gt;

     

script src =“@ Url.Content(”〜/ Scripts / jquery.unobtrusive-ajax.min.js“)”type =“text / javascript”&gt;

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

2 个答案:

答案 0 :(得分:4)

我认为发布一个表单víaajax只会导致客户端错误。

服务器端错误,需要通过Json返回,然后“插入”标记víjQuery或普通javascript。

Here you can see and download a fully working example.

答案 1 :(得分:0)

在主文件(layout.cshtml)中写下以下引用:

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

在web.config中,设置&#39; false&#39;到了&#39; true&#39;:

<appSettings>
<!--<add key="ClientValidationEnabled" value="true"/> (enable this when client-side validation is needed) -->
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

在模型中:

public class ValidUserNameAttribue : ValidationAttribute
{
  public override bool IsValid(object value)
  {
    return (value != null && value.ToString() == "Bob");
  }
}

public class Customer
{
  [ValidUserNameAttribue(ErrorMessage = "please type user name as Bob")] /* for server side validation*/
  public string UserName { get; set; }
}

在控制器中:

public class HomeController : Controller
{
  [HttpGet]
  public ActionResult Index()
  {
    return View(new ValidationModel());
  }

  [HttpPost]
  public ActionResult Form(ValidationModel validationModel)
  {
    return PartialView(!ModelState.IsValid ? "Partial/_Form" : "Partial/_Success", validationModel);
  }
}

索引视图:

@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel

@{
    ViewBag.Title = "ajax form submit and server side validation";
}


<div id="FormContainer">
    @Html.Partial("Partial/_Form")
</div>

表单视图:

@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel

@using (Ajax.BeginForm("Form", new AjaxOptions() { UpdateTargetId = "FormContainer" , OnSuccess = "$.validator.unobtrusive.parse('form');" }))
{

    <p>
        @Html.ValidationMessageFor(m => m.UserName) // (Error Message)
    </p>

    <p>
        @Html.LabelFor(m => m.UserName):
        @Html.EditorFor(m => m.UserName)
    </p>

    <input type="submit" value="Submit" />
}

成功观点:

@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel

User name '@Model.UserName' is valid :)

在AJAX表单中查看此链接以进行服务器端验证:http://www.codeproject.com/Articles/460893/Unobtrusive-AJAX-Form-Validation-in-ASP-NET-MVC