What's a good way to mimic Web Forms RadioButtonList in ASP.NET MVC?
I have View Model List like this:
public class PersonViewModel
{
  int PersonId
  bool LikesIceCream
}
The View will display a list of people and their preference to ice cream - like it or don't.
I'm not sure how to construct the html in开发者_高级运维 a way that I can use the RadioButtonFor HTML helper and properly pass the values back to the controller. Simply creating RadioButtonFor's in a foreach loop doesn't help because they will have the same name. Any idea how I can hook these values up with the model binder?
Thanks.
View model:
public class PersonViewModel
{
    public int PersonId { get; set; }
    public bool LikesIceCream { get; set; }
}
Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[]
        {
            new PersonViewModel { PersonId = 1, LikesIceCream = true },
            new PersonViewModel { PersonId = 2, LikesIceCream = false },
            new PersonViewModel { PersonId = 3, LikesIceCream = true },
        };
        return View(model);
    }
    [HttpPost]
    public ActionResult Index(IEnumerable<PersonViewModel> model)
    {
        // you will get what you need here inside the model
        return View(model);
    }
}
View (~/Views/Home/Index.cshtml):
@model IEnumerable<PersonViewModel>
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}
Editor template (~/Views/Home/EditorTemplates/PersonViewModel.cshtml):
@model PersonViewModel
<div>
    @Html.HiddenFor(x => x.PersonId)
    @Html.RadioButtonFor(x => x.LikesIceCream, "true") Yes
    @Html.RadioButtonFor(x => x.LikesIceCream, "false") No
</div>
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论