[c#] MVC3 DropDownListFor - a simple example?

I'm having trouble with DropDownListFor in my MVC3 app. I was able to use StackOverflow to figure out how to get them to appear on the View, but now I don't know how to capture the values in its corresponding properties on the View Model when it's submitted. In order to get this to work I had to create an inner class that had an ID and a value property, then I had to use an IEnumerable<Contrib> to satisfy the DropDownListFor parameter requirements. Now, however, how is MVC FW supposed to map the value that is selected on this drop-down back into the simple string property on my view model?

public class MyViewModelClass
{
    public class Contrib
    {
        public int ContribId { get; set; }
        public string Value { get; set; }
    }

    public IEnumerable<Contrib> ContribTypeOptions = 
        new List<Contrib>
        {
            new Contrib {ContribId = 0, Value = "Payroll Deduction"},
            new Contrib {ContribId = 1, Value = "Bill Me"}
        };

    [DisplayName("Contribution Type")]
    public string ContribType { get; set; }
}

In my View I place the dropdown on the page like this:

<div class="editor-label">
    @Html.LabelFor(m => m.ContribType)
</div>
<div class="editor-field">
    @Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId, 
             new SelectList(Model.ContribTypeOptions, "ContribId", "Value"))
</div>

When I submit the form the ContribType is (of course) null.

What is the correct way to do this?

This question is related to c# asp.net-mvc-3 html.dropdownlistfor

The answer is


     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value


I think this will help : In Controller get the list items and selected value

public ActionResult Edit(int id)
{
    ItemsStore item = itemStoreRepository.FindById(id);
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                        "Id", "Name",item.CategoryId);

    // ViewBag to pass values to View and SelectList
    //(get list of items,valuefield,textfield,selectedValue)

    return View(item);
}

and in View

@Html.DropDownList("CategoryId",String.Empty)

For binding Dynamic Data in a DropDownList you can do the following:

Create ViewBag in Controller like below

ViewBag.ContribTypeOptions = yourFunctionValue();

now use this value in view like below:

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to html.dropdownlistfor

onchange event for html.dropdownlist Populating a razor dropdownlist from a List<object> in MVC Fill drop down list on selection of another drop down list twitter bootstrap autocomplete dropdown / combobox with Knockoutjs MVC3 DropDownListFor - a simple example? Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables How to write a simple Html.DropDownListFor()?