你能幫我嗎,使用視圖模型從視圖控制器獲取多個表資料作為串列。下面是我的代碼它的作業,直到將多個模型傳遞給 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();
}
uj5u.com熱心網友回復:
嘗試用 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)
{
....
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415867.html
標籤:
