0

vs2012 /WebSite Razor2 开发模式,可以使用以下方法验证吗?

那么如何使用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="登录" />
4

1 回答 1

2

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

下面是一个使用 System.ComponentModel.DataAnnotations 的 ViewModel 示例:

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
于 2013-02-06T02:43:18.750 回答