Search code examples
asp.net-mvcasp.net-mvc-4partial-viewshtml.dropdownlistforviewbag

how to send list item to dropdown in a partial view on multiple pages


I am having some problem in showing data in dropdown on multiple pages. Scenario: I have 5 pages with same partial view on all these pages.In this partial view, there are two dropdown. Now, there are two controller one is Home controller and another is Post Controller. Home controller's index action method is:

public ActionResult Index()
{
    List<City> allCity = new List<city>();
    using (ApplicationDbContext dc = new ApplicationDbContext())
    {
       allCity = dc.Cities.OrderBy(a => a.CityName).ToList();
    }
    ViewBag.CityId = new SelectList(allCity, "Id", "CityName");
    return View();
}

Now, in partial view, i am sending data to dropdown like this:

@model App.Models.City

<div class="dropdown">
@Html.DropDownList("Id", ViewBag.CityId as SelectList, new { @class = "short_dropdown" })

and rendering this partial view to all the pages like this:

<section class="container">
   @Html.Partial("_CommentBox")

Now, if i see the index.cshtml page of Home Controller then values in dropdown are properly populated. But, if i go to index page of Post controller then error is:**

There is no ViewData item of type 'IEnumerable' that has the key 'Id'. System.InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'Id'.

How to resolve this. Should I have to send data along with partial view. If yes, then I have two dropdown in one partial view then how to send data for these two dropdown.


Solution

  • In your Post controller make the same as you did in your Home controller in order to populate ViewBag.CityId. And to avoid code duplication you could move it to a separate method that can be reused:

    public static List<City> GetCities()
    {
        using (ApplicationDbContext dc = new ApplicationDbContext())
        {
            return dc.Cities.OrderBy(a => a.CityName).ToList();
        }
    }
    

    and then populate ViewBag.CityId in both your controllers:

    ViewBag.CityId = new SelectList(SomeDomain.GetCities(), "Id", "CityName");