2012-01-24 45 views
0

如何從MVC3 Razor中的數據庫中獲取單選按鈕選項。每個問題我有4個選項,選項應該從數據庫填充並且應該分組。MVC3-數據庫中的Radion Button分組和綁定

@Html.RadioButtonFor(model => Model.AAAa, 'Y', new { title = "Please check this if AAA has been updated" }) 
       Yes 

這給我硬編碼的值爲Yes,但文本需要填充數據庫表。

我該如何將選定的值綁定回數據庫?一個例子會更有幫助。

謝謝

回答

7

與往常一樣開始通過定義將代表你會在視圖中處理信息的視圖模型:

public class MyViewModel 
{ 
    public string SelectedValue { get; set; } 

    // In your question you seem to be dealing with a title attribute as well 
    // If this is the case you could define a custom view model ItemViewModel 
    // which will contain the Value, the Text and the Title properties for 
    // each radio button because the built-in SelectListItem class that I am using here 
    // has only Value and Text properties 
    public SelectListItem[] Items { get; set; } 
} 

那麼你就寫一個控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel 
     { 
      // Obviously those will come from your database or something 
      Items = new[] 
      { 
       new SelectListItem { Value = "Y", Text = "Yes" }, 
       new SelectListItem { Value = "N", Text = "No" }, 
       new SelectListItem { Value = "D", Text = "Dunno" } 
      } 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     return View(model); 
    } 
} 

then then a view view:

@model MyViewModel 
@using (Html.BeginForm()) 
{ 
    for (int i = 0; i < Model.Items.Count; i++) 
    { 
     @Html.RadioButtonFor(x => x.SelectedValue, Model.Items[i].Value, new { id = "item_" + i }) 
     @Html.Label("item_" + i, Model.Items[i].Text) 
     <br/> 
    } 
    <button type="submit">OK</button> 
} 

或使視圖更小凌亂,你可以寫一個自定義的HTML幫助,這將使得那些單選按鈕,供您:

public static class HtmlExtensions 
{ 
    public static IHtmlString RadioButtonListFor<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> expression, 
     IEnumerable<SelectListItem> items 
    ) 
    { 
     var sb = new StringBuilder(); 
     var i = 0; 
     foreach (var item in items) 
     { 
      var id = string.Format("item{0}", i++); 
      var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }); 
      var label = htmlHelper.Label(id, item.Text); 
      sb.AppendFormat("{0}{1}<br/>", radio, label); 
     } 

     return new HtmlString(sb.ToString()); 
    } 
} 

,現在你的看法,都只是:

@model MyViewModel 

@using (Html.BeginForm()) 
{ 
    @Html.RadioButtonListFor(x => x.SelectedValue, Model.Items) 
    <button type="submit">OK</button> 
}  

這顯然更好看。