多个表单元素绑定到一个模型属性

问题描述:

我有一个模型多个表单元素绑定到一个模型属性

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)%> 

这个问题的最佳方法是什么?

对于该视图,我非常有信心jQuery可以确保只为bar选择了一个值。但是,如果可以避免这会更好。

在控制器方面,我对如何去约束这个问题有点失落?

型号:

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'); 
     } 
    }); 
});