【问题标题】:ValidationSummary on partial View部分视图上的 ValidationSummary
【发布时间】:2015-02-07 05:57:42
【问题描述】:

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

学生监督:

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"); }

局部视图“创建”:

@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 而不显示ValidationMessageValidationSummary

我应该改变什么来保留错误信息?

【问题讨论】:

  • 你应该返回到相同的视图,比如 return this.view(your model) 而不是redirecttoAction
  • @frebin francis,如果我这样做了,我只会得到没有列表视图的创建视图。

标签: asp.net-mvc validation razor asp.net-mvc-partialview


【解决方案1】:

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

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);
    }
}

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

【讨论】:

  • 非常感谢先生。
猜你喜欢
  • 2013-07-25
  • 1970-01-01
  • 2019-08-09
  • 2015-02-15
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 2011-12-26
相关资源
最近更新 更多