局部视图的验证摘要

ValidationSummary on partial View

我有一个列出所有学生并提示用户添加新学生的页面。

学生管理员:

public ActionResult Index()
{
    return View(db.getStudents());
}

public ActionResult Create(Student student)
{
    if (ModelState.IsValid)
    {
        //some code here
    }
    else
    {
       return RedirectToAction("Index");
    }
}

部分视图 'Index':

@model IEnumerable<Student>
@Html.DisplayNameFor(model => model.StudentName)
@foreach (var item in Model) {
    @Html.DisplayFor(modelItem => item.StudentName)
}
@{ Html.RenderAction("Create", "Student"); }

部分视图 'Create':

@model Student
@using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
    @Html.ValidationSummary(true, "")
    @Html.LabelFor(model => model.StudentName)
    @Html.EditorFor(model => model.StudentName)
    @Html.ValidationMessageFor(model => model.StudentName, "")
    <input type="submit" value="Create" />
}

我的问题:

当我 post 调用表单 Create 操作时,如果模型无效,它会重定向到 Index,而不显示 ValidationMessageValidationSummary

我应该更改什么以保留错误消息?

您需要一个视图模型来完成从单个页面列出学生和创建学生的要求。

public class IndexViewModel
{
   public IEnumerable<Student> Students {get;set;}

   public Student NewStudent {get;set;}
}

Index.cshtml:

@model IndexViewModel //Have the fully qualified model name here
@Html.DisplayNameFor(model => model.StudentName)
@foreach (var item in Model.Students) {
    @Html.DisplayFor(modelItem => item.StudentName)
}
@{ Html.RenderAction("Create", "Student", Model.NewStudent); }

控制器:

public ActionResult Index()
{
    var viewModel = new IndexViewModel();
    viewModel.Students = db.getStudents();
    viewModel.NewStudent = new Student();
    return View(db.getStudents());
}

public ActionResult Create(Student student)
{
    var viewModel = new IndexViewModel();            

    if (ModelState.IsValid)
    {
        // Create student
        // Do something else
    }
    else
    {
       viewModel.Students = db.getStudents();
       viewModel.NewStudent = student;
       return View("Index", viewModel);
    }
}

希望这对您有所帮助。这只是一个示例。您可以重构创建视图模型的代码。