我试图在for IList<Hole>
中收集数据后将视图中的loop
ViewModel发送到控制器以传递给方法,但是,传递的ViewModel仍然是空值。我错过了什么没有将ViewModel从View传递给Controller?
我的ViewModel是:
public class HoleViewModel : IEnumerable
{
public int FacilityId { get; set; }
public int CourseId { get; set; }
//public Hole Hole { get; set; }
public IList<Hole> Holes { get; set; }
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
我的观点是:
@using GT_App.Models
@model GT_App.ViewModel.HoleViewModel
....
<form method="post" action="/Hole/Create">
<fieldset>
<div>
@{
var holeCount = 4;
}
<table style="display: inline">
<thead>
<th>Number</th>
<th>Yardage</th>
<th>Par</th>
<th>Hdcp</th>
</thead>
@for (int i = 0; i < holeCount; i++)
{
<tr>
<td>
@Html.TextBoxFor(m => m.Holes[i].Number)
</td>
<td>
@Html.TextBoxFor(m => m.Holes[i].Yardage)
</td>
<td>
@Html.TextBoxFor(model => model.Holes[i].Par)
</td>
<td>
@Html.TextBoxFor(model => model.Holes[i].Handicap)
</td>
</tr>
}
</table>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
我的控制器是:
public ActionResult Create()
{
ViewBag.FacilityId = new SelectList(db.Facilities, "FacilityId", "Name");
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(HoleViewModel holes)
{
if (ModelState.IsValid)
{
for (int i = 0; i < holes.Holes.Count; i++)
{
var item = new Hole();
if (Session["FacilityId"] != null || Convert.ToInt32(Session["FacilityId"]) != 0)
{
item.FacilityId = Convert.ToInt32(Session["FacilityId"]);
}
if (Session["CourseId"] != null || Convert.ToInt32(Session["CourseId"]) != 0)
{
item.CourseId = Convert.ToInt32(Session["CourseId"]);
}
item.Number = Convert.ToInt32(Request.Form["Number" + i]);
item.Yardage = Convert.ToInt32(Request.Form["Yardage" + i]);
item.Par = Convert.ToInt32(Request.Form["Par" + i]);
item.Handicap = Convert.ToInt32(Request.Form["Handicap" + i]);
holes.Holes.Add(item);
}
// itterate thru collection to add individual holes to Entity
foreach (Hole hole in holes)
{
db.Holes.Add(hole);
db.SaveChanges();
}
//return RedirectToAction("Index");
}
ViewBag.CourseId = new SelectList(db.Courses, "CourseId", "Name", Session["CourseId"]);
//return View(Session["CourseId"]);
return RedirectToAction("Index");
}
答案 0 :(得分:0)
如果您的第二个Create
操作中出现模型验证错误,那么通常您会使用提交的模型再次返回视图,然后会在网页上显示验证错误。
您没有这样做 - 无论模型是否有效,您都会重定向到Index
操作。我会在调用RedirectToAction
之后立即拨打SaveChanges
电话,然后在方法return View(holes);
的结尾处。{/ p>
哦,我不会把SaveChanges
调用放在循环中。在循环之后执行此操作。该代码还有其他问题,但我会停在那里......: - )