如何解决如何在 mvc 中使用 ViewModel 从视图到控制器获取多个列表
你能帮我吗,使用视图模型从视图控制器获取多个表数据作为列表。下面是我的代码它的工作直到将多个模型传递给视图。我无法从控制器 Action Method 中的 View 获取这些更新的值以更新数据。
我有两个模型。
public class Teacher
{
public int TeacherId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
将模型中的模型作为列表传递
public class ViewModel
{
public IEnumerable<Teacher> Teachers { get; set; }
public IEnumerable<Student> Students { get; set; }
}
在控制器中,我定义了视图模型
[HttpGet]
public ActionResult IndexViewModel()
{
ViewModel mymodel = new ViewModel();
mymodel.Teachers = GetTeachers();
mymodel.Students = GetStudents();
return View(mymodel);
}
在我的视图中,我的所有值都正确,但是当我更改值时提交相同。更新的数据无法获取操作方法。请帮我解决这个问题。
@using MultipleModelInOneView;
@model ViewModel
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<table>
<tr>
<th>Id</th>
<th>Code</th>
<th>Name</th>
</tr>
@foreach (Teacher teacher in Model.Teachers)
{
<tr>
<td>@Html.DisplayFor(model => @teacher.TeacherId)</td>
<td>@Html.EditorFor(model => @teacher.Code)</td>
<td>@Html.EditorFor(model => @teacher.Name)</td>
</tr>
}
</table>
<p><b>Student List</b></p>
<table>
<tr>
<th>Id</th>
<th>Code</th>
<th>Name</th>
<th>Enrollment No</th>
</tr>
@foreach (Student student in Model.Students)
{
<tr>
<td>@Html.DisplayFor(model => @student.StudentId)</td>
<td>@Html.EditorFor(model => @student.Code)</td>
<td>@Html.EditorFor(model => @student.Name)</td>
</tr>
}
</table>
<input type="submit" value="Save" class="btn btn-primary" />
}
这里我无法从视图中获取列表
[HttpPost]
public ActionResult IndexViewModel("Here I'm not able to Get List from View")
{
return View();
}
解决方法
尝试用 for 循环替换 foreach 循环
@for (var i=0; i < Model.Teachers.Count; i+=1)
{
<tr>
<td>@Html.DisplayFor(model =>model.Teachers[i].TeacherId)</td>
<td>@Html.EditorFor(model => model.Teachers[i].Code)</td>
<td>@Html.EditorFor(model => model.Teachers[i].Name)</td>
</tr>
}
@for (var i=0; i < Model.Students.Count; i+=1)
{
<tr>
<td>@Html.DisplayFor(model => model.Students[i].StudentId)</td>
<td>@Html.EditorFor(model => model.Students[i].Code)</td>
<td>@Html.EditorFor(model => model.Students[i].Name)</td>
</tr>
}
和控制器动作
public ActionResult IndexViewModel(ViewModel viewModel)
{
....
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。