模型验证是检查引用的模型对象中的必填字段,当只需要一个键时

时间:2014-02-23 11:16:25

标签: c# asp.net-mvc-4 model-validation

我正在为学生模型创建一个编辑表单:

public class Student
{
    [Key]
    public virtual int ID { get; set; }

    [Required]
    public virtual StudentGuardian Guardian { get; set; }
}

这名学生里面有一个StudentGuardian实例,StudentGuardian在姓名,性别等方面有验证属性

public class StudentGuardian
{
    [Key]
    public virtual int ID { get; set; }

    [Required]
    public virtual string Name { get; set; }

    [Required]
    public virtual string MobilePhone { get; set; }

    [Required]
    public virtual Sex Sex { get; set; }
}

但在学生编辑表格中,我只对GuardianId感兴趣。关键在于创建编辑表单并在表单中创建类似的内容:

@Html.DropDownListFor(x => x.Student.Guardian.ID, <GUARDIANS_LIST>)

由于Student模型需要Guardian对象,因此MVC验证要求我输入Guardian.Name和Guardian.MobilePhone等,

如何才能将验证强制为Guardian.Id只有整个对象?

1 个答案:

答案 0 :(得分:2)

StudentGuardian保留在Student中的唯一想法是在StudentStudentGuardian类之间创建一对一关系,而不是将数据呈现给{ {1}}。通过您的方法,您不仅会在编辑学生实体时以及在创建学生实体时遇到错误。尝试使用其他人推荐的视图模型。以下只是帮助您更好地理解的尝试。

view

然后在控制器的public class StudentViewModel { public int StudentId { get; set; } public string Name { get; set; } //..other member variables.. [Display(Name="Guardian"] public int GuardianId { get; set; } public virtual IEnumerable<StudentGuardian> Guardians { get; set; } } 操作中

Edit

[HttpGet] public ActionResult Edit(int id = 0) { Student student = db.Students.Find(id); var model = new StudentViewModel(); model.Name = student.Name; model.Guardians = db.Guardians.ToList(); //or if using repository then call the method that fetches //.. you the list of objects //..and bind it to the StudentViewModel instance created. //Other Properties you need..fetch and assign them here.. //model.StudentId= student.Id; ... etc if (student == null) { return HttpNotFound(); } return View(model); // return the viewModel instance. } 与[{1}}绑定在一起。

Edit View

StudentViewModel

的引用上接收数据
@model MvcApplication.Models.ViewModels.StudentViewModel
@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Student</legend>

        @Html.HiddenFor(model => model.StudentId)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.GuardianId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.GuardianId)
            @Html.DropDownListFor(model => model.GuardianId, new SelectList(Model.Guardians, "GuardianId", "GuardianName"),"Select")
        </div>


        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

尝试使用google搜索ViewModels,您将获得大量资源。