2011-09-27 30 views
1

我查看型号列表如下:在ASP.NET MVC中模拟Web窗体RadioButtonList的好方法是什么?

public class PersonViewModel 
{ 
    int PersonId 
    bool LikesIceCream 
} 

视图将显示人的名单和他们的偏爱冰淇淋 - 喜欢还是不知道。

我不知道如何构建html,我可以使用RadioButtonFor HTML帮助程序并正确地将值传递回控制器。只需在foreach循环中创建RadioButtonFor就无济于事,因为它们将具有相同的名称。任何想法如何将这些值与模型联编程序绑定?

谢谢。

+0

为什么单选按钮?为什么不选择复选框?这是否意味着你只能有一个喜欢冰淇淋的人?似乎相当严格的应用程序:-) –

+0

@Darin对不起,有人员记录列表。 – Mike

+0

好的,你想在视图上用这个列表做什么? –

回答

1

视图模型:

public class PersonViewModel 
{ 
    public int PersonId { get; set; } 
    public bool LikesIceCream { get; set; } 
} 

控制器:

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

视图(~/Views/Home/Index.cshtml):

@model IEnumerable<PersonViewModel> 

@using (Html.BeginForm()) 
{ 
    @Html.EditorForModel() 
    <input type="submit" value="OK" /> 
} 

编辑模板(~/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> 
+0

噢,很好,我想我明白了。因此EditorForModel实际上正在考虑正确连接每个单选按钮,以便它可以正确绑定到模型。谢谢! – Mike

相关问题