带有静态内容的Html.dropdownlist

时间:2013-11-28 12:21:10

标签: c# asp.net asp.net-mvc asp.net-mvc-4 html-helper

我正在开发一个asp.net mvc Web应用程序,在我的高级搜索页面上,我希望有三个html.dropdownlist包含静态值: -

  1. 完全匹配

  2. 开头

    我需要将下拉列表放在任何搜索字段旁边。

    所以我可以建议如何创建这样的静态html.dropdownlist,因为我所拥有的所有当前下拉列表都填充了我模型中的动态数据?

    由于

3 个答案:

答案 0 :(得分:12)

您的第一个选择是在视图中包含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"}})

如果在您的网站上大量使用它,我更喜欢的第三个选项是创建一个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" } });
}

答案 1 :(得分:4)

为什么在仅使用静态数据时需要HTML帮助程序?

<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)

答案 2 :(得分: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;
    }
}

现在在Controller中调用静态类

public ActionResult Index()
{

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

最后一次在视图中调用ViewBag

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