1
votes

I am developing an ASP.Net MVC 3 web application. The app currently is connected to a database that has several tables, two of which are Category(catId, Name) and Site(siteID, Name).

I wish to create a view that has two drop down lists, one for each of the tables mentioned, so that the user can select from and then run a report. To do this I have created a viewModel to represent the two drop down lists

public class ReportSiteCategorySearchViewModel
{
    public SelectList categoryList { get; set; }
    public SelectList siteList { get; set; }
}

Then in my controller that returns the viewModel I have the following

public ActionResult getEquipmentByCategoryAndSite()
    {
        ReportSiteCategorySearchViewModel viewModel = new ReportSiteCategorySearchViewModel
        {
            categoryList = new SelectList(categoryService.GetAllCategories().ToList(), "categoryID", "categoryTitle"),
            siteList = new SelectList(siteService.GetAllSites().ToList(), "siteID", "title")
        };

        return View(viewModel);
    }

I then pass to a view which takes this viewModel and writes out the values to the drop downs

<div>
    <label for="ddlSite">Sites</label>
    @Html.DropDownList("ddlSite", Model.siteList, "All Sites")
    &nbsp;&nbsp;
    <label for="ddlCatgeory">Categories</label>
    @Html.DropDownList("ddlCatgeory", Model.categoryList, "All Categories")
</div>

This works, however, I am not sure this is the best way to do it. I am just wondering is my method correct, is there a better way to do this? Ie, what if I needed 5/6 more drop down lists from other tables, should I just add to the current viewModel etc?

Any feedback would be much appreciated.

Thank You.

1

1 Answers

0
votes

You can create a viewModel of type List<SelectList> In your controller, add each table (as a SelectList as you're doing) to this model. Then pass the view the model, which is a list of SelectLists.

Then you can iterate through each value in your view:

<div>
@foreach(SelectList SL in Model)
{
   <label for="ddl"+SL>SL.Title</label>
   @Html.DropDownList("ddl"+SL.Title, sl.list, sl.items")
}

You may need to modify your list of SelectList to include the 'Title' or 'items' field. By doing it this way you can keep adding elements to the List, and you won't need to update the view.