Rectangle 27 23

Actually, you just have to pass in null for the Html.DropDownList(). I was having the same exact problem, and used the Reflector to look at the MVC Source Code.

System.Web.Mvc.Extensions.SelectExtensions
SelectInternal()
null
SelectList

Here is the "Code-behind".

ViewData["MyDropDown"] = new SelectList(selectListItems,
                             "Value",
                             "Text",
                             selectedValue.ToString()
                         );

Here is the HTML view code.

<%= Html.DropDownList("MyDropDown", null,
        "** Please Select **",
        new { @class = "my-select-css-class" }
    ) %>

Note: I'm using ASP.NET MVC 2.0 (Beta Version).

After extensively using ASP.NET MVC for the past 3 years, I prefer using additionalViewData from the Html.EditorFor() method more.

anonymous
Html.EditorFor()
<%= Html.EditorFor(
    m => m.MyPropertyName,
    new { MyPropertyName = Model.ListItemsForMyPropertyName }
) %>

Thanks ... that's the best solution for this problem with strongly typed views, I have ever seen ... It works with Model that has property name which matches the drop down name, and so it should ... thanks

I agree. The "rename your field" mantra kills model binding to objects up front. This was the best solution for me as well.

i think this breaks if the property is part of an array

ASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model - S...

asp.net-mvc html-helper
Rectangle 27 5

After a bunch of hemming and hawing it boils down to the following line of code

if (ViewData.ModelState.TryGetValue(key, out modelState))

which means MVC is trying to resolve the value by only looking at the ViewData Dictionary<> object and not traversing down into the ViewData.Model object.

Whether that's a bug, limitation or design decision I'm not sure. However, you can fix it the following way:

<%= Html.TextBox("MyTextBox", ViewData.Model.MyTextBox) %>

Thanks for the suggestion Todd, As I mentioned in the post, if using a model you can get around it with: var model{ MyList = new SelectList(items, "Value", "Text", selected_value) } and just: <%=Html.DropDownList("MyList")%>

Its mainly just the behaviour that was puzzling me - least you've given me a start now - think I need to figure out the whole ModelState flow - if its coming out of there then there must be a step that loads stuff from ViewData etc

Hey ... this is not even an answer ... how could you pick this up ?? You can not set the selected value in Html extension method, you have to do it in the controller when building the ViewData

ASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model - S...

asp.net-mvc html-helper
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 95

Can't you make the field readonly="readonly" instead of disabled="disabled"? A readonly field value will be submitted to the server while still being non-editable by the user. A SELECT tag is an exception though.

readonly works but it doesn't gray out the field. Here is an example I am using: <%: Html.TextBoxFor(model => model.p1, new { @readonly = "readonly" }) %> how can I gray it out so visually it looks like it is not editable. Better yet can we use something similar to LabelFor, I tried LabelFor but it only gets the DisplayName....

4 years doing .net asp and I never knew that disabled inputs don't get poste back... how did that pass me? Just include a Hidden field for the disabled select and its all sorted.(Even though the ID's are repeated on the form which is not allowed)

<select>
type="checkbox"

I'm trying to do the same thing with radio buttons but readonly doesn't seem to work on them.

c# - How do I submit disabled input in ASP.NET MVC? - Stack Overflow

c# .net javascript asp.net-mvc
Rectangle 27 2

try setting the selected value in the controller action when creating the SelectList collection.

This solved the problem for me when trying to have a selected value for a dropdownlist's items. Thank you!

ASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model - S...

asp.net-mvc html-helper
Rectangle 27 2

I'm obviously late here. But I wanted to add this comment incase someone else came across this issue.

In MVC 2. You can do the following to select the item...

public ActionResult Edit(int id)
        {
            Team team = _db.TeamSet.First(m => m.TeamID == id);
            var fanYear = from c in _db.FanYearSet select c;
            ViewData["FantasyYear"] = new SelectList(fanYear, "YearID", "FantasyYear", team.FanYearReference.EntityKey.EntityKeyValues[0].Value);
            var league = from c in _db.LeagueSet select c;
            ViewData["League"] = new SelectList(league, "LeagueID", "League_Name", team.LeaguesReference.EntityKey.EntityKeyValues[0].Value);

            return View(team);
        }

The fourth parameter takes a value and will select the value you want in the dropdownlist. In my example I have a table called team and it is I have a relationship set to a table called fanYear and league.

You can see that I first get the team that I'm editing, then building a dropdownlist of fantasy year and another for leagues. In order to determine the year and league for the team, I had to use Entity Reference.

Just wanted to put that out there. I couldn't find any examples of doing this.

ASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model - S...

asp.net-mvc html-helper
Rectangle 27 27

document.getElementById("Costo").readOnly = true;
document.getElementById("Costo").style.color = "#c0c0c0";

This didn't quite work for me (figured it out thanks to this SO link). This worked: textBox.Attributes.Add("readonly", "readonly"); and the explanation is in the link

That's good that you edited it as this is making more sense for me.

readonly seems to be way to go. It doesn't do weird things like not posing the control back but doesn't allow to edit it. Muchas Gracias!

Not working with checkbox control

c# - How do I submit disabled input in ASP.NET MVC? - Stack Overflow

c# .net javascript 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.

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 121

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 9

@Html.DropDownList("country", new SelectList(ViewBag.countries), "-select- ", new { @class="chzn-select", @style="width:160px;" })

drop down menu - asp.net mvc How to add placeholder for html.dropdownl...

asp.net-mvc drop-down-menu placeholder
Rectangle 27 9

@Html.DropDownList("country", new SelectList(ViewBag.countries), "-select- ", new { @class="chzn-select", @style="width:160px;" })

drop down menu - asp.net mvc How to add placeholder for html.dropdownl...

asp.net-mvc drop-down-menu placeholder
Rectangle 27 17

@Html.EditorFor(model => model.userName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })

The key change is to wrap the html attributes in the "new { htmlAttributes =" <your desired attributes> "}" strings. This appears to be unique pattern for the EditorFor (different that DisplayFor, DropdownFor, etc.)

asp.net mvc 3 - MVC3 EditorFor readOnly - Stack Overflow

asp.net-mvc-3 readonly editorfor
Rectangle 27 7

Html.DropdownList(name, selectList, optionLabel)
@Html.ValidationMessage("Cat")

"-Select Category-" is still not showing up..

@Html.DropDownList("Cat", new SelectList(ViewBag.Categories, "ID", "CategoryName"), "-Select Category-")

c# - validate a dropdownlist in asp.net mvc - Stack Overflow

c# asp.net-mvc razor
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 23

HTML input elements such as textboxes that have the disabled="disabled" attribute will never send their values to the server when the form is submitted. If you want to send the value to the server while still disabling the user from changing it you could make the textbox readonly:

<%= Html.TextBoxFor(model => model.TotalAmount, new { @readonly = "readonly" }) %>

@Darin Dimitrov, you said "...will never send their values to the server...". Is this a general rule or MVC specific? Also your solution is for textboxes. What about select elements?

@Anar, no this has nothing to do with ASP.NET MVC. It's basic HTML. And it is true for all input elements including select.

The thing is, select does not support the readonly attribute. I have found a workaround to store the value of dropdown in a hidden element. I don't like that approach, but unfortunately I will have to use it as a last resort.

asp.net mvc disabled text box updated by javascript does not post new ...

asp.net-mvc asp.net-mvc-3
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 17

@ppumkin mentioned this on his comment on this answer but I wanted to highlight it as I was unable to find other resources on submitting data from a disabled <select>. I also believe it is relevant to the question as selects are not <input>s but they are "input"s.

Just include a Hidden field for the disabled select and its all sorted.

@Html.DropDownListFor(model => model.SelectedID, ... , new { disabled = "disabled"}) @* Won't be posted back *@
@Html.HiddenFor(model => model.SelectedID) @* Will be posted back *@

Caution: this will put two tags on the page with the same ID, which is not really valid HTML and could cause headaches with javascript. For me, I have javascript to set the value of the dropdown by its html id, and if you put the hidden field first, the javascript will find that instead of the select.

c# - How do I submit disabled input in ASP.NET MVC? - Stack Overflow

c# .net javascript asp.net-mvc
Rectangle 27 17

Typically, if I have a field that is "read-only" but needs to be submitted back to the server, I will make the display disabled (or simply text), but then add a hidden field with the same name. You still need to make sure that the field is not actually modified on the server-side -- just don't update it from the model in your action -- but the model state will still be accurate if there are errors.

Yes, I was thinking of doing what you're sugesting. But I would had to handle more variables. I'm hopping that may be my post will appear in google and people won't have to suffer, looking for an easy solution.

One problem with your solution is that it breaks if javascript is disabled. Injecting the hidden field server-side doesn't have this issue.

c# - How do I submit disabled input in ASP.NET MVC? - Stack Overflow

c# .net javascript 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