我正在制作一个基于 ASP .NET MVC4 的应用程序。我是那个领域的新手。这个想法很简单——在数据库中有一些成员,列出它们,通过复选框选择所需的成员,然后重定向到其他控制器,该控制器将对先前选择的成员执行某些操作。
问题是将成员列表从视图传递到控制器。我认为它可以与 ViewModel 一起使用。它当然适用于从控制器到视图,但不是相反。
我的视图模型:
public class MembersViewModel
{
public IEnumerable<Directory_MVC.Models.Member> MembersEnum { get; set; }
public string Test { get; set; }
}
我的控制器的片段:
public class MembersController : Controller
{
private MainDBContext db = new MainDBContext();
public ActionResult Index()
{
var model = new Directory_MVC.ViewModels.MembersViewModel();
// populating from DB
model.MembersEnum = db.Members.Include(m => m.Group).Include(m => m.Mother).Include(m => m.Father);
model.Test = "abc";
return View(model);
}
[HttpPost]
public ActionResult GoToSendEmail(Directory_MVC.ViewModels.MembersViewModel returnedStruct)
{
if (ModelState.IsValid)
{
// it is valid here
return Redirect("http:\\google.com");
}
}
我的观点片段:
@model Directory_MVC.ViewModels.MembersViewModel
@{
ViewBag.Title = "Members listing";
var lineCount = 0;
string lineStyle;
}
@using (Html.BeginForm("GoToSendEmail", "Members", FormMethod.Post))
{
<table>
@foreach (var item in Model.MembersEnum)
{
lineCount++;
// set styling
if (lineCount % 2 == 1)
{
lineStyle = "odd-line";
}
else
{
lineStyle = "even-line";
}
<tr class="@lineStyle">
<td>
@Html.EditorFor(modelItem => item.Selected)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Mother.FirstName) @Html.DisplayFor(modelItem => item.Mother.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Father.FirstName) @Html.DisplayFor(modelItem => item.Father.LastName)
</td>
<!-- other print-outs but not all properties of Member or Mother/father are printed -->
</tr>
}
</table>
<input type="submit" value="Send E-mail" />
}
数据在视图中显示正常。但是,当我提交该表单时,在 Controller 的 GoToSendEmail 方法中,returnedStruct.MembersEnum 和 Test 字符串都为空。
是否有错误或是否有另一种可能的方式来传递该成员结构并检查其 Selected 属性?