我有一个表单,在我的表单中,用户可以填写他们的详细信息并选择他们在复选框中的兴趣。我将兴趣部分放在一个表格中作为局部视图。
表格有,
我有一个模型,其中包含Name,BirthDay,Place等所有字段。 还有LookFormodel的另一个模型。
现在我提交表格时。所有字段,如名称,生日和地点都参与模型,但我没有获得复选框选择项目列表。
如何在表单提交中获取复选框值?
答案 0 :(得分:4)
这似乎是编辑模板的一个很好的候选者。我们一如既往地设计视图模型:
public class MyViewModel
{
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DateOfBirth { get; set; }
public string Place { get; set; }
public IEnumerable<InterestViewModel> Interests { get; set; }
}
public class InterestViewModel
{
public int Id { get; set; }
public string InterestLabel { get; set; }
public bool IsSelected { get; set; }
}
然后是控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Name = "john",
DateOfBirth = new DateTime(1990, 1, 1),
Place = "Spain",
Interests = new[]
{
new InterestViewModel { Id = 1, InterestLabel = "cinema" },
new InterestViewModel { Id = 2, InterestLabel = "sport" },
new InterestViewModel { Id = 3, InterestLabel = "books" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO: process the results here, the view model will be
// correctly bound
....
}
}
然后是视图(~/Views/Home/Index.cshtml
)
@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
</div>
<div>
@Html.LabelFor(x => x.DateOfBirth)
@Html.EditorFor(x => x.DateOfBirth)
</div>
<div>
@Html.LabelFor(x => x.Place)
@Html.EditorFor(x => x.Place)
</div>
<h2>Interests</h2>
@Html.EditorFor(x => x.Interests)
<button type="submit">OK</button>
}
以及将为Interests集合(~/Views/Home/EditorTemplates/InterestViewModel.cshtml
)的每个元素呈现的相应编辑器模板:
@model InterestViewModel
@Html.LabelFor(x => x.IsSelected, Model.InterestLabel)
@Html.CheckBoxFor(x => x.IsSelected)
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.InterestLabel)