2011-09-27 64 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

相關問題