Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Dropdown lists in MVC...basically the bane of my existence...

I've seen numerous topics on this exact issue, but everything I've found on here and around the Internet haven't solved my issue.

A bit of background first: I have a page that allows users to edit a record. One of those fields on the edit page is a Dropdown list filled with clients. To get to the edit page, the user clicks on an Edit link from another page with a table of records on it. When they get to the edit page, the form is populated with the information from the selected record to edit. Besides a login screen, it's probably one of the most basic and common features to ANY website that moves data around.

So, here's the code from the View:

@Html.DropDownList("ClientsDropdown", (IEnumerable<SelectListItem>)ViewBag.ClientsDropdown, "Select a Client")

And here's the code in the Controller:

[HttpGet]
    public ViewResult Details(int id, int pageNumber = 1)
    {
        Invoice invoice = db.Invoices.Find(id);
        FillClientDropdown(invoice);
        var model = new InvoiceDetailsModel() { Invoice = invoice, PageNumber = pageNumber };
        return View(model);
    }

And FillClientDropdown(invoice) calls:

private void FillClientDropdown(Invoice invoice)
    {
        var clientList = db
            .Clients
            .OrderBy(x => x.Name)
            .ToList()
            .Select(x => new SelectListItem
            {
                Selected = (x.ID == invoice.ClientOcrStringID),
                Text = x.Name,
                Value = x.ID.ToString()
            });

        ViewBag.ClientsDropdown = new SelectList(clientList, "Value", "Text", "Selected");
    }

I've already confirmed that clientList does in fact get a nice list of clients from the database, and that the proper SelectListItem has the "Selected" attribute set to True.

But when I load up the page and Inspect the Dropdown list, this is what I get:

<select id="ClientsDropdown" name="ClientsDropdown">
<option value="">Select a Client</option>
<option value="1">Test Client 1</option>
<option value="2">Test Client 2</option>

I would have guessed that creating a new SelectList would also add in a Selected="something" value for each option, but that doesn't seem to be the case.

Any help with this issue would be greatly appreciated, as it's rather frustrating to know that I could have done this in about 3 minutes if I were able to use Web Forms...

UPDATE

Looks like I got it working!

Here's what I did: I already had an InvoiceDetailsModel to work with, so I added:

public SelectList ClientList { get; set; }

Then, in my InvoiceController, I changed up my Details a bit:

[HttpGet]
    public ViewResult Details(int id, int pageNumber = 1)
    {
        Invoice invoice = db.Invoices.Find(id);
        var clientList = db
            .Clients
            .OrderBy(x => x.Name)
            .ToList()
            .Select(x => new SelectListItem
            {
                Text = x.Name,
                Value = x.ID.ToString()
            });
        var model = new InvoiceDetailsModel() { Invoice = invoice, PageNumber = pageNumber };
        model.ClientList = new SelectList(clientList, "Value", "Text", model.Invoice.ClientOcrStringID);
        return View(model);
    }

to take advantage of my addition to the InvoiceDetailsModel. Finally, in my view, I changed my Dropdown to this:

@Html.DropDownListFor(model => model.Invoice.ClientOcrStringID, Model.ClientList, "Select a Client")

I'm hoping this helps someone...anyone in the future.

share|improve this question
 
I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". –  John Saunders Jun 12 '13 at 17:29
 
Oops, sorry about that! –  user1059903 Jun 12 '13 at 17:31
add comment

1 Answer

up vote 1 down vote accepted

Refactore your code the way to not use the ViewBag or the ViewData. It sound silly but it will work and you will have a better code.

What you have to do:

  • Create a ViewModel class, it can derive from the Invoice class
  • Add plus properties: pageNumber and the SelectList
  • In the view use the DropDownListFor helper
share|improve this answer
 
Well, I'm working on someone else's code, so I don't have the luxury of rewriting a whole lot of it. I did, however, find out that they do have a ViewModel class that I can use. The problem that I'm running into is how to go about setting that SelectedValue property. –  user1059903 Jun 12 '13 at 18:10
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.