开发者

Adding global blank option to DroDownList in MVC

开发者 https://www.devze.com 2022-12-31 20:46 出处:网络
Is there a way of using a templated helper in mvc so that each and every select list in my project has a custom default \'Choose an option\' with null value etc.

Is there a way of using a templated helper in mvc so that each and every select list in my project has a custom default 'Choose an option' with null value etc.

The posts I have seen seem a little complex, is it possible to have a DropDownList.ascx file in shared view folder with something like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SelectListItem>>" %>
<%= Html.DropDownList(selectlist name, select开发者_如何学Clist value, "Choose an option")%>

And then having a UIHint("DropDownList") for each dropdownlist in the ViewModel? Some guidance on syntax of parameters would be much appreciated, where name and value of the viewmodel dropdownlist plus the 'Choose an option' string are passed.

Or is this all wishful thinking?


there is no point in having separate view, as the dropdown list will just create the html tag, you can have a HTML Extension to fix your problem partially,

create a Extension method something like this

public static string MyDropDownList(this HtmlHelper htmlHelper, IEnumerable<SelectListItem> selectList) {
    return Html.DropDownList(selectlist name, selectlist value, "Choose an option");
}

and from your view you can create dropdownlist

<%= Html.MyDropDownList(selectlist name, selectlist value)%>

if you want to change the text "Choose an option" to "Select an option" you just need to change the extension method.

0

精彩评论

暂无评论...
验证码 换一张
取 消