請您幫助我,使用視圖模型從視圖控制器中獲取多個表的資料作為串列。下面是我的代碼,它在將多個模型傳遞給視圖之前一直在作業。我無法在控制器的動作方法中從視圖中獲得這些更新的值來更新資料。
我有兩個模型。
public class Teacher
{
public int TeacherId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class Student 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; }
在控制器中,我定義了視圖模型
[]
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>代碼</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>學生名單</b></p>
<table>
<tr>
<th>Id</th>
<th>代碼</th>
<th>姓名</th>
<th>入學編號</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("這里我無法從View獲取List")
{
return View()。
}
uj5u.com熱心網友回復:
嘗試用for回圈代替foreach回圈
@for (var i=0; i < Model.Teaches.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/shujuku/319232.html
標籤:
上一篇:ASP.netMVC自定義索賠
