我有一个列出所有学生的页面,并提示用户添加新学生。
学生管理员:
public ActionResult Index()
{
return View(db.getStudents());
}
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
//some code here
}
else
{
return RedirectToAction("Index");
}
}
部分视图'索引':
@model IEnumerable<Student>
@Html.DisplayNameFor(model => model.StudentName)
@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.StudentName)
}
@{ Html.RenderAction("Create", "Student"); }
部分视图&#39;创建&#39;:
@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" />
}
我的问题:
当我发布调用的表单Create
时,如果模型无效,则重定向到Index
,不显示ValidationMessage
和ValidationSummary
。
我应该更改什么才能保留错误消息?
答案 0 :(得分:2)
您需要有一个视图模型来完成列出学生和从单个页面创建学生的要求。
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);
}
}
希望这会有所帮助。这只是一个样本。您可以重构创建视图模型的代码。