2012-09-09 40 views
1

我有一個看起來像這樣的視圖模型的子對象上 -MVC 3 - 客戶端驗證視圖模型

public class upgradeViewModel 
{ 
    public Cart Cart { get; set; } 
    public RegisterModel RegisterModel { get; set; } 
} 

視圖模型包含了一個名爲RegisterModel屬性RegisterModel模型對象類似於此 -

public class RegisterModel 
{ 
    [Required] 
    [Display(Name = "Your name")] 
    public string UserName { get; set; } 

    [Required] 
    [DataType(DataType.EmailAddress)] 
    [Display(Name = "Your email address")] 
    public string Email { get; set; } 

    ... 
} 

我使用視圖模型的RegisterModel屬性設置了一個表格,在使用upgradeViewModel對象,因爲它是模型的視圖。在提交表單時,我沒有得到任何客戶端驗證,但我確實獲得了RegisterModel對象的服務器端驗證。

我相信我已經正確配置了一切正確的工作,而且它可以在網站的其他區域工作。我是否需要額外做些事情來讓客戶端驗證適用於視圖模型的子對象?

這裏是我的看法碼 -

@model upgradeViewModel 

@{ 
    ViewBag.Title = "Title"; 
    Layout = "~/Views/Shared/_LayoutNormal.cshtml"; 
} 

<h2>Title</h2> 

Some text .... 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.") 
    <div> 
     <fieldset> 
      <legend>Your Information</legend> 

      <div class="editor-label"> 
       @Html.LabelFor(m => m.RegisterModel.UserName) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(m => m.RegisterModel.UserName) 
       @Html.ValidationMessageFor(m => m.RegisterModel.UserName) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(m => m.RegisterModel.Email) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(m => m.RegisterModel.Email) 
       @Html.ValidationMessageFor(m => m.RegisterModel.Email) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(m => m.RegisterModel.Password) 
      </div> 
      <div class="editor-field"> 
       @Html.PasswordFor(m => m.RegisterModel.Password) 
       @Html.ValidationMessageFor(m => m.RegisterModel.Password) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(m => m.RegisterModel.ConfirmPassword) 
      </div> 
      <div class="editor-field"> 
       @Html.PasswordFor(m => m.RegisterModel.ConfirmPassword) 
       @Html.ValidationMessageFor(m => m.RegisterModel.ConfirmPassword) 
      </div> 

      <p> 
       <input type="submit" value="Save Details" class="inputbutton" /> 
      </p> 
     </fieldset> 
    </div> 
} 

回答

0

你應該確保以下的AppSettings在web.config文件。你已經在你的頁面上引用了jquery.validate.unobtrusive.min.js。 (這應該是在你的MVC項目的腳本文件,當您創建它)

<add key="ClientValidationEnabled" value="true" /> 
<add key="UnobtrusiveJavaScriptEnabled" value="true" />