Display Selected value with Html.DropDownList in ASP.Net MVC

I wrote ToastManager about two months ago, and not try to covert it into ASP.Net. What ToastManager does is to collect people’s toast order for the morning toast run.

Why? I just think MVC is cool. It separate programming logic into 3 different layers nicely.

The first problem I encountered in writing MVC code was to find a way to display a dropdownlist with a selected value. It is funny. I feel like I am a complete novice when I use MVC.

Simply, you need to pass the selected value in creating SelectList. (from ASP.NET MVC Html.DropDownList SelectedValue)

for example,

    Slices = new SelectList(new int[] {1, 2, 3, 4}, 2);
[

The below is the code for my OrderFormViewModel class


public Models.Order Order { get; private set; }
public string[] Spread { get; private set; }
public SelectList Slices { get; private set; }

public OrderFormViewModel(Order order)
{
    Order = order;
    Spread = new[] { "Butter", "Jam", "Peanut Butter", "Bovril", "Honey", "Marmalade", "Marmite", "Vegemite" };
    int[] sliceList = new int[] {1, 2, 3, 4};
    Slices = new SelectList(sliceList, Order.Slice);
}

Display Selected value with Html.DropDownList in ASP.Net MVC

4 thoughts on “Display Selected value with Html.DropDownList in ASP.Net MVC

  1. Roger says:

    //Simply, you need to pass the selected value in creating SelectList.

    => This is a non-sence. What if I lopp over a collection with 50 or so records and need to set different value for each of the DropDownLists. Your suggestion works just in basic scenario.

    => I cannot find how to solve this, your comment did not help. I think, as usually, it is better to skip Microsoft’s control and create my own :-(.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s