【发布时间】:2014-01-28 02:17:06
【问题描述】:
我正在尝试获取用户选中复选框的 Id 值列表。这是模型:
using System.Collections.Generic;
namespace TestWebApplication3.Models
{
public class TestViewModel
{
public IEnumerable<InnerViewModel> ModelData { get; set; }
public class InnerViewModel
{
public int Id { get; set; }
public bool Checked { get; set; }
}
}
}
控制器:
using System.Web.Mvc;
using TestWebApplication3.Models;
namespace TestWebApplication3.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var test = new TestViewModel();
test.ModelData = new[]
{
new TestViewModel.InnerViewModel {Id = 10},
new TestViewModel.InnerViewModel {Id = 20},
new TestViewModel.InnerViewModel {Id = 30},
new TestViewModel.InnerViewModel {Id = 40}
};
return View(test);
}
[HttpPost]
public string TestAction(TestViewModel model)
{
string s = "";
foreach (TestViewModel.InnerViewModel innerViewModel in model.ModelData)
{
if (innerViewModel.Checked)
s += innerViewModel.Id + " ";
}
return s;
}
}
}
还有观点:
@model TestWebApplication3.Models.TestViewModel
@using (Html.BeginForm("TestAction", "Home"))
{
<ol>
@foreach (var testData in Model.ModelData)
{
<li>
@Html.HiddenFor(m => testData.Id)
@Html.CheckBoxFor(m => testData.Checked)
</li>
}
</ol>
<input type="submit"/>
}
所以我将 InnerViewModel 对象列表(在 Index 操作中创建)显示为复选框。当用户提交表单时,我想以某种方式获取在 TestAction 方法中“检查”的 Id 值列表。但返回的模型始终为空。
在我正在制作的应用程序中,模型有更多属性,因此将 InnerViewModel 对象列表嵌套在 TestViewModel 中很重要。我也不想使用 MvcCheckBoxList 之类的第三方解决方案,因为在我看来对于这样一个简单的任务来说太过分了。
谁能向我解释这个工作缺少什么?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 razor