2013-02-06 43 views
0

Vs2012/WebSite Razor2开发模式,可以使用以下方法验证?关于MVC4用户输入,如何不依赖实体(模型)输入验证?

那么如何使用MVC的类似方法呢?

// Setup validation 
Validation.RequireField("email", "You must specify an email address."); 
Validation.RequireField("password", "You must specify a password."); 
Validation.Add("password", 
    Validator.StringLength(
     maxLength: Int32.MaxValue, 
     minLength: 6, 
     errorMessage: "Password must be at least 6 characters")); 

<ol> 
    <li class="email"> 
     <label for="email" @if (!ModelState.IsValidField("email")) 
      {<text>class="error-label"</text>}>电子邮件地址</label> 
     <input type="text" id="email" name="email" value="@email" @Validation.For("email")/> 
     @* 将任何用户名验证错误写入页中 *@ 
     @Html.ValidationMessage("email") 
    </li> 
    <li class="password"> 
     <label for="password" @if (!ModelState.IsValidField("password")) {<text>class="error-label"</text>}>密码</label> 
     <input type="password" id="password" name="password" @Validation.For("password")/> 
     @* 将任何密码验证错误写入页中 *@ 
     @Html.ValidationMessage("password") 
    </li> 
    <li class="remember-me"> 
     <input type="checkbox" id="rememberMe" name="rememberMe" value="true" checked="@rememberMe" /> 
     <label class="checkbox" for="rememberMe">记住我?</label> 
    </li> 
</ol> 
<input type="submit" value="登录" /> 

回答

2

或许,如果你正试图避免使用模型,你可以使用强类型是利用System.ComponentModel.DataAnnotations库视图模型对象。您可以注释ViewModel类的每个属性,然后Razor将读取注释并进行适当的验证。然后,在您的控制器中,您只需在回发之前检查是否(ModelState.IsValid)。比使用AutoMapper将ViewModel属性映射到模型。

这里是一个视图模型使用System.ComponentModel.DataAnnotations的例子:

public class PropertyViewModel 
{ 
    public int Id { get; set; } 
    [Required] 
    public PropertyType PropertyType { get; set; } 
    [Required] 
    public string Address { get; set; } 
    [Required] 
    public string City { get; set; } 
    [Required] 
    public StateFullName State { get; set; } 
    [Required] 
    public string Zip { get; set; } 
} 

添加到您的视图:

@model PropertyViewModel