我有一个模型
public class Foo
{
public string bar { get; set; }
//Other stuff
}
在我看来,我需要向用户展示两个单选按钮和一个下拉列表,下拉列表充当组中的第三个单选按钮。
<%= Html.RadioButtonFor(m => m.bar, "A") %>
<%= Html.RadioButtonFor(m => m.bar, "B") %>
<%= Html.DropDownListFor(m => m.bar, ViewData["OtherUncommonOptions"] as SelectList)%>
解决这个问题的最佳方法是什么?
对于 View ,我非常有信心 jQuery 可以确保只为 bar
选择一个值。但是,如果可以避免这种情况,那就更好了。
在 Controller 方面,我有点不知道如何绑定(bind)它?
最佳答案
型号:
public class Foo
{
public string Bar { get; set; }
}
Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["OtherUncommonOptions"] = new SelectList(
Enumerable.Range(1, 5).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = "item " + x
}),
"Value",
"Text"
);
return View(new Foo());
}
[HttpPost]
public ActionResult Index(Foo model)
{
// model.Bar will contain the selected value here
return View(model);
}
}
查看:
<% using (Html.BeginForm()) { %>
<%= Html.RadioButtonFor(m => m.Bar, "A", new { id = "barA" }) %>
<%= Html.RadioButtonFor(m => m.Bar, "B", new { id = "barB" }) %>
<%= Html.DropDownListFor(
m => m.Bar,
ViewData["OtherUncommonOptions"] as SelectList,
"-- value --",
new { id = "barDDL" }
) %>
<input type="submit" value="OK" />
<% } %>
最后一部分是确保使用 javascript,如果选择了两个单选按钮之一,下拉列表将清除其值,如果在下拉列表中选择了一个值,则取消选择单选按钮。
$(function() {
$('#barA, #barB').click(function () {
$('#barDDL').val('');
});
$('#barDDL').change(function () {
if ($(this).val() != '') {
$('#barA, #barB').removeAttr('checked');
}
});
});
关于c# - 绑定(bind)到一个模型属性的多个表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6118183/