2013-11-28 107 views
1

我工作的一個asp.net MVC Web應用程序,和我的高級搜索頁上,我想有三個html.dropdownlist包含靜態值: -Html.dropdownlist靜態內容

  1. 完全匹配

  2. 開始有了

,我需要的dropdownlists是任何搜索字段的旁邊。

所以,任何一個建議如何我可以創建這樣的靜態html.dropdownlist,因爲所有目前的dropdownlists,我有充滿動態數據從我的模型填充?

謝謝

+0

看到同樣的問題是在這裏回答http://stackoverflow.com/questions/5576257/bind-html -dropdownlist-with-static-items –

+0

儘管如此,請參閱我的擴展方法。 :) @VishalPandey我也加了我的答案。 – hutchonoid

回答

11

你的第一個選項是包括您的視圖中的HTML:

<select id="selection"> 
    <option>Exact match</option> 
    <option>Starts with</option> 
</select> 

第二個選擇是使用硬編碼的內置HTML幫手:

@Html.DropDownList("selection", new List<SelectListItem>() {new SelectListItem { Text="Exact match", Value = "Match"}, new SelectListItem { Text="Starts With", Value = "Starts"}}) 

t這如果是使用了很多在您的網站,我寧願赫德選擇是創建一個HTML輔助擴展,你可以簡單地使用它像這樣:

@Html.SearchSelectionList() 

下面是該代碼:

public static MvcHtmlString SearchSelectionList(this HtmlHelper htmlHelper) 
{ 
    return htmlHelper.DropDownList("selection", new List<SelectListItem>() { new SelectListItem { Text = "Exact match", Value = "Match" }, new SelectListItem { Text = "Starts With", Value = "Starts" } }); 
} 
4

爲什麼在只使用靜態數據時需要HTML-helper?

<select id="myDropDownList" name="myDropDownList"> 
    <option value="volvo">Volvo</option> 
    <option value="saab">Saab</option> 
    <option value="mercedes">Mercedes</option> 
    <option value="audi">Audi</option> 
</select> 

或者這也許是:

@{ 
var list = new SelectList(new [] 
    { 
     new {ID="1", Name="volvo"}, 
     new {ID="2", Name="saab"}, 
     new {ID="3", Name="mercedes"}, 
     new {ID="4", Name="audi"}, 
    }, 
    "ID", "Name", 1); 
} 
@Html.DropDownList("list", list) 
1

你可以參考這個Bind Dropdownlist In Mvc4 Razor

讓我們嘗試這種方式也

public static class DDLHelper 
{ 
    public static IList<SelectListItem> GetGender() 
    { 
     IList<SelectListItem> _result = new List<SelectListItem>(); 
     _result.Add(new SelectListItem { Value = "2", Text = "Male" }); 
     _result.Add(new SelectListItem { Value = "1", Text = "Female" }); 
     return _result; 
    } 
} 

中立即撥打控制器

public ActionResult Index() 
{ 

    ViewBag.Gender = new SelectList(DDLHelper.GetGender(), "Value", "Text"); 
    return View(); 
} 

靜態類在過去,現在ViewBag呼叫鑑於

@Html.DropDownList("gender", new SelectList(ViewBag.Gender, "Value", "Text"), "--Select--")