Rectangle 27 5

Html.DropDownList
htmlAttributes

you can use this overload:

@Html.DropDownList("statusList", null, String.Empty, new { disabled = "disabled"})

you have to use following overload:

Html.DropDownList(
    string name,
    IEnumerable<SelectListItem> selectList,
    string optionLabel,
    IDictionary<string, Object> htmlAttributes
)

c# - How to create dropdownlist Disabled in ASP.NET Razor MVC 5 - Stac...

c# asp.net asp.net-mvc razor asp.net-mvc-5
Rectangle 27 120

I bumped into the same problem, found this question, and thought that the solution provided by Ash wasn't what I was looking for; Having to create the HTML myself means less flexibility compared to the built-in Html.DropDownList() function.

Turns out C#3 etc. makes this pretty easy. I have an enum called TaskStatus:

var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
               select new { ID = s, Name = s.ToString() };
ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);

This creates a good ol' SelectList that can be used like you're used to in the view:

<td><b>Status:</b></td><td><%=Html.DropDownList("taskStatus")%></td></tr>

The anonymous type and LINQ makes this so much more elegant IMHO. No offence intended, Ash. :)

good answer! i was hoping someone would use linq and the SelectList :) Glad i checked here first!

ID = s give me the DataTextField not the value ? What might be the reason ? Thank you

Rune, I used this same method and the DropDownList DOES render yet when it posts to the server, it doesn't save the value I had selected.

select new { ID = (int)s, Name = s.ToString() };

This is the answer I like the most because of its simplicity. Shame you didn't receive enough credit since the selected answer used your solution.

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 120

I bumped into the same problem, found this question, and thought that the solution provided by Ash wasn't what I was looking for; Having to create the HTML myself means less flexibility compared to the built-in Html.DropDownList() function.

I bumped into the same problem, found this question, and thought that the solution provided by Ash wasn't what I was looking for; Having to create the HTML myself means less flexibility compared to the built-in Html.DropDownList() function.

Turns out C#3 etc. makes this pretty easy. I have an Enum called TaskStatus:

Turns out C#3 etc. makes this pretty easy. I have an enum called TaskStatus:

var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
               select new { ID = s, Name = s.ToString() };
ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);
var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
               select new { ID = s, Name = s.ToString() };
ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);

This creates a good ol' SelectList that can be used like you're used to in the view:

This creates a good ol' SelectList that can be used like you're used to in the view:

<td><b>Status:</b></td><td><%=Html.DropDownList("taskStatus")%></td></tr>
<td><b>Status:</b></td><td><%=Html.DropDownList("taskStatus")%></td></tr>

The anonymous type and LINQ makes this so much more elegant IMHO. No offence intended, Ash. :)

The anonymous type and LINQ makes this so much more elegant IMHO. No offence intended, Ash. :)

good answer! i was hoping someone would use linq and the SelectList :) Glad i checked here first!

ID = s give me the DataTextField not the value ? What might be the reason ? Thank you

ID = s give me the DataTextField not the value ? What might be the reason ? Thank you

Rune, I used this same method and the DropDownList DOES render yet when it posts to the server, it doesn't save the value I had selected.

select new { ID = (int)s, Name = s.ToString() };

Rune, I used this same method and the DropDownList DOES render yet when it posts to the server, it doesn't save the value I had selected.

select new { ID = (int)s, Name = s.ToString() };

This is the answer I like the most because of its simplicity. Shame you didn't receive enough credit since the selected answer used your solution.

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 67

ViewData["DealerTypes"] = Helper.SetSelectedValue(listOfValues, selectedValue) ;
<%=Html.DropDownList("DealerTypesDD", ViewData["DealerTypes"] as SelectList)%>

It appears that the DropDown must not have the same name has the ViewData name :S weird but it worked.

+1 for "the DropDown must not have the same name has the ViewData name" Big Thanks

Thankyou!!! You just solved my problem after many hours of wondering why this didn't work :)

This works for selected value, but a problem arises when you try to update "DealerTypes" in the db since it is the DropDownList is now bound to "DealerTypesDD" which doesn't exist in the model. A workaround is to add a hidden field and htmlAttributes to the DropDownList: <input type="hidden" name="DealerTypes" id="DealerTypes" value="" /> <%= Html.DropDownList("DealerTypesDD", ViewData["DealerTypes"] as SelectList, new { @onchange = "DealerTypes.value = this.value"})%>

You're better of adding 'DS' to the viewdata name, thus not ruining the model binding...

What the hell! This is not fixed in MVC5??? As another trick mentioned by @Paul Hatcher , copy the selected id into the ViewData["DealerTypes"].

ASP.NET MVC Html.DropDownList SelectedValue - Stack Overflow

asp.net-mvc
Rectangle 27 48

public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
}
var list = new[] {   
    new Person { Id = 1, Name = "Name1" }, 
    new Person { Id = 2, Name = "Name2" }, 
    new Person { Id = 3, Name = "Name3" } 
};

var selectList = new SelectList(list, "Id", "Name", 2);
ViewData["People"] = selectList;

Html.DropDownList("PeopleClass", (SelectList)ViewData["People"])
<select id="PeopleClass" name="PeopleClass">
    <option value="1">Name1</option>
    <option selected="selected" value="2">Name2</option>
    <option value="3">Name3</option>
</select>

This was helpful in tracking down the cause. I have updated my question to reflect the additions.

is first in model? second in controller? and third in view it clear, but 2 first ones..???

Good answer, but isn't it better to use a ViewModel?

ASP.NET MVC Html.DropDownList SelectedValue - Stack Overflow

asp.net-mvc
Rectangle 27 178

You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?

@Shyju Sorry, I was missing the @ prefix of the readonly property. See my edit.

In the future, if you get any kind of errors adding properties to the dynamic object argument you can prefix them with the @. You'll usually only see it with keywords that match HTML attributes (like readonly, class, etc.)

@BradChristie: No; you only need an @ to use attributes that match C# keywords.

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly", @class="form-control" })

c# - How to create readonly textbox in ASP.NET MVC3 Razor - Stack Over...

c# asp.net-mvc-3 razor html-helper readonlyattribute
Rectangle 27 29

@Html.CheckBoxFor(m => m.IsPublished, new { @disabled = "disabled" })

Assuming that your class AdvSlot contains a property IsPublished you can write in your loop:

<td>
    @Html.CheckBox(item.AdvSlotId + "_IsPublished", item.IsPublished, new { @disabled = "disabled" });
</td>

Please note MyProperty is a Property in the ViewModel any idea how to solve it? thanks

@GibboK: could you, please, include your viewmodel as well?

Bad solution, disabled checkboxes are not passed back in the post.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

asp.net mvc - Razor how to create a CheckBox and make it READONLY? - S...

asp.net-mvc asp.net-mvc-3 razor
Rectangle 27 4

@{
    var itemTypesList = new List<SelectListItem>();
    itemTypesList.AddRange(Enum.GetValues(typeof(ItemTypes)).Cast<ItemTypes>().Select(
                (item, index) => new SelectListItem
                {
                    Text = item.ToString(),
                    Value = (index).ToString(),
                    Selected = Model.ItemTypeId == index
                }).ToList());
 }


@Html.DropDownList("ItemTypeId", itemTypesList)

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 4

@{
    var itemTypesList = new List<SelectListItem>();
    itemTypesList.AddRange(Enum.GetValues(typeof(ItemTypes)).Cast<ItemTypes>().Select(
                (item, index) => new SelectListItem
                {
                    Text = item.ToString(),
                    Value = (index).ToString(),
                    Selected = Model.ItemTypeId == index
                }).ToList());
 }


@Html.DropDownList("ItemTypeId", itemTypesList)
@{
    var itemTypesList = new List<SelectListItem>();
    itemTypesList.AddRange(Enum.GetValues(typeof(ItemTypes)).Cast<ItemTypes>().Select(
                (item, index) => new SelectListItem
                {
                    Text = item.ToString(),
                    Value = (index).ToString(),
                    Selected = Model.ItemTypeId == index
                }).ToList());
 }


@Html.DropDownList("ItemTypeId", itemTypesList)

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 47

ASP.NET has built-in request validation that automatically helps protect against XSS and HTML injection attacks. If you want to explicitly disable this validation you could decorate the action you are posting to with the [ValidateInput(false)] attribute:

[HttpPost]
[ValidateInput(false)]   
public ActionResult SaveArticle(ArticleModel model)
{
    var JResult = new JsonResult();
    if (ModelState.IsValid)
    {
        ...
    }
    return JResult;
}

Also if you are running this on ASP.NET 4.0 for this attribute to take effect you need to add the following to your web.config:

And if you are using ASP.NET MVC 3.0 you could decorate only the property on your model that requires HTML with the [AllowHtml] attribute:

public class ArticleModel 
{
    [AllowHtml]
    public string SomeProperty { get; set; }

    public string SomeOtherProperty { get; set; }
}

Also in your javascript function you probably want serialize() instead of serializeArray():

function JqueryFromPost(formId) {
    var form = $(formId);
    $.post(form.action, form.serialize(), function (data) {
        //Getting the data Result here...
    });
}
<httpRuntime requestValidationMode="2.0" />

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Post HTML tag (codes) as string with ASP.net MVC & JQuery - Stack Over...

jquery asp.net-mvc ajax
Rectangle 27 657

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new { @class = "form-control" })
@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })
namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}
ViewData["taskStatus"] = task.Status.ToSelectList();
using MyApp.Common

I couldnt get it worked, could you please help. When i do Post.PostType.ToSelectList(); it doesnt recognise the extension ?

I could not get this to work either. Is Status your Enum Property on the task class? Isn't this one of the enumerated values?

You can restrict it a little bit with: where T : struct, IConvertible See: stackoverflow.com/questions/79126/

This is cool. If anyone is struggling w/ implementation here's how I did it. Added an EnumHelpers class to the HtmlHelpers folder. Used the above code. Added the namespace per @TodK recommendation: <add namespace="xxx.HtmlHelpers" />. Then I used it in a razor page like such: @Html.DropDownListFor(model => model.Status, @Model.Status.ToSelectList()) HTH

ASP.NET MVC

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 657

@Html.EnumDropDownListFor(
    x => x.YourEnumField,
    "Select My Type", 
    new { @class = "form-control" })
@Html.DropDownList("MyType", 
   EnumHelper.GetSelectList(typeof(MyType)) , 
   "Select My Type", 
   new { @class = "form-control" })
namespace MyApp.Common
{
    public static class MyExtensions{
        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
            return new SelectList(values, "Id", "Name", enumObj);
        }
    }
}
ViewData["taskStatus"] = task.Status.ToSelectList();
using MyApp.Common

I couldnt get it worked, could you please help. When i do Post.PostType.ToSelectList(); it doesnt recognise the extension ?

I could not get this to work either. Is Status your Enum Property on the task class? Isn't this one of the enumerated values?

You can restrict it a little bit with: where T : struct, IConvertible See: stackoverflow.com/questions/79126/

This is cool. If anyone is struggling w/ implementation here's how I did it. Added an EnumHelpers class to the HtmlHelpers folder. Used the above code. Added the namespace per @TodK recommendation: <add namespace="xxx.HtmlHelpers" />. Then I used it in a razor page like such: @Html.DropDownListFor(model => model.Status, @Model.Status.ToSelectList()) HTH

ASP.NET MVC

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 5

You can still name the DropDown as "UserId" and still have model binding working correctly for you.

The only requirement for this to work is that the ViewData key that contains the SelectList does not have the same name as the Model property that you want to bind. In your specific case this would be:

This will produce a select element that is named UserId, which has the same name as the UserId property in your model and therefore the model binder will set it with the value selected in the html's select element generated by the Html.DropDownList helper.

I'm not sure why that particular Html.DropDownList constructor won't select the value specified in the SelectList when you put the select list in the ViewData with a key equal to the property name. I suspect it has something to do with how the DropDownList helper is used in other scenarios, where the convention is that you do have a SelectList in the ViewData with the same name as the property in your model. This will work correctly:

// in my controller
ViewData["UserId"] = new SelectList(
    users, 
    "UserId", 
    "DisplayName", 
    selectedUserId.Value); // this has a value

// in my view
<%=Html.DropDownList("UserId")%>

Thanks a lot mate, above all answers this worked for me, dont know why but it did

Finally! After hours of trying I finally found your "only requirement". That did it.

ASP.NET MVC Html.DropDownList SelectedValue - Stack Overflow

asp.net-mvc
Rectangle 27 321

I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute.

I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute.

public enum TestEnum
{
  [Description("Full test")]
  FullTest,

  [Description("Incomplete or partial test")]
  PartialTest,

  [Description("No test performed")]
  None
}
public enum TestEnum
{
  [Description("Full test")]
  FullTest,

  [Description("Incomplete or partial test")]
  PartialTest,

  [Description("No test performed")]
  None
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

 ...

 private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }

    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

    public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = from value in values
            select new SelectListItem
            {
                Text = GetEnumDescription(value),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            };

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

 ...

 private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }

    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

    public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = from value in values
            select new SelectListItem
            {
                Text = GetEnumDescription(value),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            };

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }

You can then do this in your view:

You can then do this in your view:

@Html.EnumDropDownListFor(model => model.MyEnumProperty)
@Html.EnumDropDownListFor(model => model.MyEnumProperty)

EDIT 2014-JAN-23: Microsoft have just released MVC 5.1, which now has an EnumDropDownListFor feature. Sadly it does not appear to respect the [Description] attribute so the code above still stands. (See http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum

EDIT 2014-JAN-23: Microsoft have just released MVC 5.1, which now has an EnumDropDownListFor feature. Sadly it does not appear to respect the [Description] attribute so the code above still stands. (See http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum

Update: It does support the DisplyName attribute [Display(Name = "Sample")] though, so one can use that.

Update: It does support the Display attribute [Display(Name = "Sample")] though, so one can use that.

+1 I found this most useful of all the answers here. I was able to turn this in to a highly reusable piece of code. Thank you!

+1 I found this most useful of all the answers here. I was able to turn this in to a highly reusable piece of code. Thank you!

Visual Studio has a strange bug where if you don't reference System.Web.Mvc.Html then it says that DropDownListFor can't be found, but neither can it resolve it. You have to manually do using System.Web.Mvc.Html;. Just so y'know.

Visual Studio has a strange bug where if you don't reference System.Web.Mvc.Html then it says that DropDownListFor can't be found, but neither can it resolve it. You have to manually do using System.Web.Mvc.Html;. Just so y'know.

I have a variant of this in a gist which we use in all of our projects: gist.github.com/1287511

I have a variant of this in a gist which we use in all of our projects: gist.github.com/1287511

Great solution, thanks, would be even better if you can cache the results of GetEnumDescription

Great solution, thanks, would be even better if you can cache the results of GetEnumDescription

The new MVC 5.1 EnumDropDownListFor doesn't use [Description("")] but it does use [Display(Name = "")]! Enjoy :)

The new MVC 5.1 EnumDropDownListFor doesn't use [Description("")] but it does use [Display(Name = "")]! Enjoy :)

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 321

I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute.

public enum TestEnum
{
  [Description("Full test")]
  FullTest,

  [Description("Incomplete or partial test")]
  PartialTest,

  [Description("No test performed")]
  None
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

 ...

 private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }

    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

    public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = from value in values
            select new SelectListItem
            {
                Text = GetEnumDescription(value),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            };

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }

You can then do this in your view:

@Html.EnumDropDownListFor(model => model.MyEnumProperty)

EDIT 2014-JAN-23: Microsoft have just released MVC 5.1, which now has an EnumDropDownListFor feature. Sadly it does not appear to respect the [Description] attribute so the code above still stands. (See http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum

Update: It does support the Display attribute [Display(Name = "Sample")] though, so one can use that.

+1 I found this most useful of all the answers here. I was able to turn this in to a highly reusable piece of code. Thank you!

Visual Studio has a strange bug where if you don't reference System.Web.Mvc.Html then it says that DropDownListFor can't be found, but neither can it resolve it. You have to manually do using System.Web.Mvc.Html;. Just so y'know.

I have a variant of this in a gist which we use in all of our projects: gist.github.com/1287511

Great solution, thanks, would be even better if you can cache the results of GetEnumDescription

The new MVC 5.1 EnumDropDownListFor doesn't use [Description("")] but it does use [Display(Name = "")]! Enjoy :)

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 70

If a control is disabled it cannot be edited and its content is excluded when the form is submitted.

This isn't necessarily true ... depending on the version of .NET, if the readonly value is changed, it will revert to the original value on the postback. You need to do something like TextBox1.Attributes.Add("readonly", "true"); to avoid this.

That should be TextBox1.Attributes.Add("readonly", "readonly"), but yes if you want the viewstate to work then you can't use either of ReadOnly or Enabled.

If a control is readonly it cannot be edited, but its content (if any) may be included with the submission. See: w3.org/TR/html4/interact/forms.html#h-17.12 "Read-only elements may be successful." This means that a browser might decide not to post back the value of a readonly input box and that would be perfectly correct.

@Anthony: That's not how I read that specification. Whether or not a control is successful depends on many factors, one of which is whether the control is disabled. (See the section immediately below what you cited). For them to say that "Read-only elements must be successful" would be wrong, because for example it could be a read-only select box with no selection made.

asp.net - asp:TextBox ReadOnly=true or Enabled=false? - Stack Overflow

asp.net textbox readonly disabled-control
Rectangle 27 9

If you want to remove the link instead of disabling it:

jQuery('#path .to .your a').each(function(){
    var $t = jQuery(this);
    $t.after($t.text());
    $t.remove();
});
  • You can also use function(k,v) to grab an iterator and the element without using 'this'
  • Feel free to replace jQuery with $ if you are using the default namespace
  • var $t = jQuery(this) is a caching function which references the element and also helps clean up the code
  • it is a good practice to precede variables which are actually jQuery items with a $ to help keep them separated visually in the code. It also helps you recognize that you can call methods on them.

asp.net mvc - Disabling links with JQuery - Stack Overflow

jquery asp.net-mvc
Rectangle 27 144

In ASP.NET MVC 5.1, they added the EnumDropDownListFor() helper, so no need for custom extensions:

public enum MyEnum
{
    [Display(Name = "First Value - desc..")]
    FirstValue,
    [Display(Name = "Second Value - desc...")]
    SecondValue
}
@Html.EnumDropDownListFor(model => model.MyEnum)
<select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">

You should create a new question that is specific to MVC 5.1 and put this as the answer, then send me a link to the post so that I may upvote an favorite.

What I don't like about EnumDropDownListFor() is that it saves into the DB the int value of the enum, not the text, so if you ever choose to add a new enum item, it must necessarily go at the end of the list, so as not to loose the relationship of the saved database int values to original positions of the enum items. That is an unnecessary restriction if the text is saved. Plus, I rather be able to look at the db and see a text, rather than ints where I then have to lookup the text values elsewhere. Otherwise this html helper is very convenient to use.

@Giovanni - you can specify your own numerical values.

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 144

In ASP.NET MVC 5.1, they added the EnumDropDownListFor() helper, so no need for custom extensions:

public enum MyEnum
{
    [Display(Name = "First Value - desc..")]
    FirstValue,
    [Display(Name = "Second Value - desc...")]
    SecondValue
}
@Html.EnumDropDownListFor(model => model.MyEnum)
<select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">

You should create a new question that is specific to MVC 5.1 and put this as the answer, then send me a link to the post so that I may upvote an favorite.

What I don't like about EnumDropDownListFor() is that it saves into the DB the int value of the enum, not the text, so if you ever choose to add a new enum item, it must necessarily go at the end of the list, so as not to loose the relationship of the saved database int values to original positions of the enum items. That is an unnecessary restriction if the text is saved. Plus, I rather be able to look at the db and see a text, rather than ints where I then have to lookup the text values elsewhere. Otherwise this html helper is very convenient to use.

@Giovanni - you can specify your own numerical values.

How do you create a dropdownlist from an enum in ASP.NET MVC? - Stack ...

asp.net asp.net-mvc
Rectangle 27 596

This problem has been addressed in ASP.Net MVC 3. They now automatically convert underscores in html attribute properties to dashes. They got lucky on this one, as underscores are not legal in html attributes, so MVC can confidently imply that you'd like a dash when you use an underscore.

@Html.TextBoxFor(vm => vm.City, new { data_bind = "foo" })

If you're still using an older version of MVC, you can mimic what MVC 3 is doing by creating this static method that I borrowed from MVC3's source code:

public class Foo {
    public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) {
        RouteValueDictionary result = new RouteValueDictionary();
        if (htmlAttributes != null) {
            foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes)) {
                result.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
            }
        }
        return result;
    }
}

And then you can use it like this:

<%: Html.TextBoxFor(vm => vm.City, Foo.AnonymousObjectToHtmlAttributes(new { data_bind = "foo" })) %>

and this will render the correct data-* attribute:

<input data-bind="foo" id="City" name="City" type="text" value="" />

Hi Simon, did you solve your problem? If not, can you provide your code that's causing you the problem?

WebGrid.GetHtml(htmlAttributes: new { data_some : "thing" })

@RubensMariuzzo this isn't baked in to the RouteValueDictionary but into MVC3's Html.Something() methods. It's possible that WebGrid hasn't been upgraded in the same way, or you could check the version on the System.Web.Helpers.dll

html5 - How to use dashes in HTML-5 data-* attributes in ASP.NET MVC -...

asp.net-mvc html5 custom-data-attribute