在ASP.NET MVC3中编辑和验证复杂模型

时间:2011-11-24 16:36:31

标签: asp.net asp.net-mvc-3 entity-framework

我有一个使用EntityFramework和SQL2008的应用程序。我正在使用DB-first方法。下面显示了我遇到问题的两个实体:

http://imageshack.us/photo/my-images/339/modelfj.jpg/

员工Edit.cshtml

的一部分
<div class="client_row">
    <label class="client_label">
        FirstName</label>
    @Html.TextBoxFor(model => model.FirstName, new { @class = "client_edit" })
    @Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="client_row">
    <label class="client_label">
        LastName</label>
    @Html.TextBoxFor(model => model.LastName, new { @class = "client_edit" })
    @Html.ValidationMessageFor(model => model.LastName)
</div>

    @Html.EditorFor(model => model.Account)

<div class="client_row">
    <span class="client_hr"></span>
    <label class="client_label">
        Email</label>
    @Html.TextBoxFor(model => model.Email, new { @class = "client_edit" })
    @Html.ValidationMessageFor(model => model.Email)
</div>

帐户编辑器文件(EditorFor用户)

@Html.HiddenFor(model => model.AccountID)
<div class="client_row">
    <label class="client_label">
        Login</label>
    @Html.TextBoxFor(model => model.Login, new { @class = "client_edit" })
    @Html.ValidationMessageFor(model => model.Login)
</div>
<div class="client_row">
    <label class="client_label">
        Password</label>
    @Html.PasswordFor(model => model.Password, new { @class = "client_edit password1" })

我的部分帐户文件用于验证

[MetadataType(typeof(Account_Validation))]
public partial class Account
{
}
[Bind(Exclude = "AccountID")]
public class Account_Validation
{
    [Required]
    [Remote("IsLoginAvailable", "Validation")]
    [Display(Name="Login")]
    public string Login { get; set; }

    [DataType(DataType.Password)]
    [Display(Name="Password")]
    public string Password { get; set; }

}

    @Html.ValidationMessageFor(model => model.Password)
</div>

当我尝试创建一名员工时,一切正常。我可以插入Employee表和Account表。我已经实现了标准的远程验证(使用数据注释)来检查登录名的可用性。

当我尝试编辑员工时问题就出现了。验证不允许我这样做,因为它说登录已经采取。嗯,这是真的,但我不想改变它。你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:0)

我要做的是为Add Employee和Edit Employee创建一个ViewModel,让它们都从一个基本的viewmodel继承

创建帐户和登录的情况类似,只是因为您正在处理同一个实体并不意味着您应该使用相同的验证逻辑。

相关问题