Opzione 1
Creare un EditorTemplate
chiamato BootstrapSelect.cshtml
@model object
<div class="form-group">
@Html.LabelFor(m => m, new { @class = "col-md-3 control-label" })
<div class="col-md-9">
@Html.DropDownListFor(m => m, (SelectList)ViewBag.Items, new { @class = "form-control"})
@Html.ValidationMessageFor(m => m, null, new { @class = "help-block" })
</div>
</div>
e nella vista
@Html.EditorFor(m => m.CategoryId, "BootstrapSelect")
ma questo significa che si avrebbe sempre puntuale necessario assegnare `ViewBag.Items nel controller
var categories = // get collection from somewhere
ViewBag.Items = new SelectList(categories, "ID", "CategoryName");
Opzione 2
Modificare il EditorTemplate
ad accettare ulteriore Viewdata
@model object
<div class="form-group">
@Html.LabelFor(m => m, new { @class = "col-md-3 control-label" })
<div class="col-md-9">
@Html.DropDownListFor(m => m, (SelectList)ViewData["selectList"], new { @class = "form-control"})
@Html.ValidationMessageFor(m => m, null, new { @class = "help-block" })
</div>
</div>
e nella vista passare il SelectList
nel additionalViewData
parametro
@Html.EditorFor(m => m.CategoryId, "BootstrapSelect", new { selectList = new SelectList(ViewBag.Categories, "ID", "CategoryName") })
questo è meglio in quanto si non è necessario affidarsi a ViewBag. Ad esempio, se si ha un modello di vista con una proprietà public SelectList CategoryItems { get; set; }
allora si potrebbe utilizzare
@Html.EditorFor(m => m.CategoryId, "BootstrapSelect", Model.CategoryItems)
Opzione 3
Crea il tuo aiuto utilizzando i metodi di supporto built-in
using System;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace YourAssembly.Html
{
public static class BootstrapHelper
{
public static MvcHtmlString BootstrapDropDownFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, SelectList selectList)
{
MvcHtmlString label = LabelExtensions.LabelFor(helper, expression, new { @class = "col-md-3 control-label" });
MvcHtmlString select = SelectExtensions.DropDownListFor(helper, expression, selectList, new { @class = "form-control" });
MvcHtmlString validation = ValidationExtensions.ValidationMessageFor(helper, expression, null, new { @class = "help-block" });
StringBuilder innerHtml = new StringBuilder();
innerHtml.Append(select);
innerHtml.Append(validation);
TagBuilder innerDiv = new TagBuilder("div");
innerDiv.AddCssClass("col-md-9");
innerDiv.InnerHtml = innerHtml.ToString();
StringBuilder outerHtml = new StringBuilder();
outerHtml.Append(label);
outerHtml.Append(innerDiv.ToString());
TagBuilder outerDiv = new TagBuilder("div");
outerDiv.AddCssClass("form-group");
outerDiv.InnerHtml = outerHtml.ToString();
return MvcHtmlString.Create(outerDiv.ToString());
}
}
}
e nella vista
@Html.BootstrapDropDownFor(m => m.CategoryId, new SelectList(ViewBag.Categories, "ID", "CategoryName"))
+1 per aggiungendo 3 opzioni –