Skip to content

Simple DropDownList With Default Value Using ASP.NET MVC4, Razor and an HtmlHelper

Updated: at 02:12 PM

First, the results of what you get.  Notice the URL parameter, the default value in the DropDownList and also the text value output on the page.

 image

Visual Studio Project Project.zip

Background

I know a lot of us are struggling changing from ASP.NET WebForms to MVC4.  For me in particular, it’s been a struggle but I’m slowly seeing light at the end of the tunnel.  Our Silicon Valley Code Camp has been in the process of rewriting in MVC4 for the past many months, and with the help of contractors (and me), we are getting there.  Basically, the site has gone from:

image

to

image

The example I’m showing here is really based on just implementing a tag cloud manager. You can see an example of this in production and in action here:

http://siliconvalley-codecamp.com/tag

image

So, let’s move to the very simple example (project file above).   The Simple Implementation

First, we need to create an empty Visual Studio 2012 MVC4 Razor project.

Then, let’s create a new home controller that looks like the following:

public ActionResult Index(int? maxCnt = 50)
{
    ViewBag.TopTags = new List<SelectListItem>
        {
            new SelectListItem
                {
                    Text = "Top 25 Tags", 
                    Value = "25",
                    Selected = checkForSelectedValue(maxCnt ?? 0,25 )
                },
            new SelectListItem {Text = "Top 50 Tags", Value = "50",Selected = checkForSelectedValue(maxCnt ?? 0,50 )},
            new SelectListItem {Text = "Top 75 Tags", Value = "75",Selected = checkForSelectedValue(maxCnt ?? 0,75 )},
            new SelectListItem {Text = "All Tags", Value = "9999",Selected = checkForSelectedValue(maxCnt ?? 0,9999 )}
        };
ViewBag.MaxCnt = maxCnt ?? 888;
<span class="kwrd">return</span> View();

}

private bool checkForSelectedValue(int cnt, int maxCnt) { return cnt == maxCnt; }

Notice we are creating a ViewBag property TopTags which is a list of SelectListItem.  SelectListItem is what is needed as part of the Html Helper will use for the dropdownlist.  Also notice that we set the default selected list value based on the passed in value to the controller.  If the passed in value equals one of the items, the Selected parameter gets set to true.

Now, let’s make a simple route that passes in maxCnt value from the URL as http://mysite.com/50 as an example.  The route is as follows

routes.MapRoute(
    name: "DropDownListRoute",
    url: "{maxCnt}",
    defaults:
        new
            {
                controller = "Home",
                action = "Index",
                maxCnt = UrlParameter.Optional
            });

Finally, we need the razor view itself.

@model dynamic

<h2>Simple DropDownList Using HTML Helpers</h2> @Html.DropDownList(“TopTags”, null, new { @onchange = “ChangeCallback(this.value);” }) <p> MaxCnt Passed In: @ViewBag.MaxCnt </p>

<script type=“text/javascript”> function ChangeCallback(maxCnt) { window.location.href = maxCnt; // redirect to “/75” } </script>

The DropDownList takes as the first parameter as the ViewBag value which is the actual list.  The third parameter is basically a call back that gets called on change of the selection box.  It pass the value of the dropdownlist to the little JavaScript function at the bottom (ChangeCallback) that simply does a new redirect to the URL with the number at the end.

Very simple!

HTHs

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects