2013-11-28 106 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--")