[英]How to remove property of model from client side validation?
在我的模型中,我有一个User
类,其中变量Password
是必需的属性。
public class User
{
public int UserId { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[Display(Name="First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name="Last Name")]
public string LastName { get; set; }
public string Address { get; set; }
[Required]
[EmailValidator(ErrorMessage = "Email entered is not valid")]
[Display(Name="Email")]
public string Email { get; set; }
}
我的EditUser
视图:
@model User
@using (Html.BeginForm("EditUser", "Users", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create User" />
</p>
}
在视图中,我在用户编辑中排除了“密码”字段,并且为了在控制器中验证模型,我使用了[Bind(Exclude="Password")]
,但是它不起作用,因此我使用了ModelState.Remove("Password");
但它在服务器端进行验证。 如果我使用所有字段(包括Password
),它将在客户端进行验证。 如何在客户端(排除一个字段时)进行验证?
我假设您的模型是数据库中的模型。 有时,数据模型不适用于视图。 为了使其正常工作,我建议您引入解决所有视图方面的不同ViewModel类。 最有可能的是您的用户模型,但没有密码字段:
public class UserViewModel
{
public int UserId { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[Display(Name="First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name="Last Name")]
public string LastName { get; set; }
public string Address { get; set; }
[Required]
[EmailValidator(ErrorMessage = "Email entered is not valid")]
[Display(Name="Email")]
public string Email { get; set; }
}
因此,不是使用“数据”模型,而是使用视图模型,然后将其在控制器中映射到数据模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.