2012-01-11 75 views
4

我相信這已被問過,但我一直在嘗試所有的解決方案,但沒有給出的解決方案是解決我的問題。可能,我沒有執行正確的。mvc3 - ajax表單提交和服務器端驗證

我正在使用MVC3,剃刀,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 = 「真」 包括

.js文件是

SCRIPT SRC = 「@ Url.Content(」 〜/ Scripts/jquery.valid.js「)」type =「text/javascript」>

script src =「@ Url.Content(」〜/ Scripts/jquery.validate.min.js「 )「type =」text/javascript「>

SCRIPT SRC = 「@ Url.Content(」 〜/腳本/ jquery.validate.unobtrusive.min.js 「)」 類型= 「文本/ JavaScript的」>

SCRIPT SRC =「@ Url.Content (「〜/ Scripts/jquery.unobtrusive-ajax.min.js」)「type =」text/javascript「>

我在這裏錯過了什麼?任何選擇? 在此先感謝。

回答

4

我認爲發佈表單víaajax你只會得到客戶端錯誤。

服務器端錯誤,需要通過Json返回,然後「插入」標記víajQuery或純javascript。

Here you can see and download a fully working example.

+1

經過大量的試驗和閱讀我eneded了做像你的建議。當存在任何服務器端錯誤時,我返回帶有false的Json作爲對象的第一個參數。在OnSucess中,我抓取錯誤檢查數據[0] == false(表示錯誤),並將其插入到ValidationSummary標記中。謝謝。 – peacefulmember 2012-01-25 17:30:21

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> 

在網頁。配置,設置 '假' 到 '真':

<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