型號:
public class Foo
{
public string Bar { get; set; }
}
控制器:
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,如果兩個單選按鈕中的一個選擇下拉列表清除其值,並且如果在下拉列表中選擇了收音機的值ns被取消選擇。
$(function() {
$('#barA, #barB').click(function() {
$('#barDDL').val('');
});
$('#barDDL').change(function() {
if ($(this).val() != '') {
$('#barA, #barB').removeAttr('checked');
}
});
});