Home > Enterprise >  Binding data from session to drop down list asp.net mvc
Binding data from session to drop down list asp.net mvc

Time:10-05

In my web application, I have added a dropdownlist for the nav bar.

There I want to load some data from the database.

So in the Home Controller, I have used a view bag option.

ViewBag.MyBranch_Id = new SelectList(BranchList, "Id", "Name");

In this view, I called it as

@Html.DropDownList("MyBranch_Id", null, new { @class = "form-control js-dropdown js-MyBranch", @Id = "Branch" })

But the issue is this dropdown I created on the layout view. So when I navigate to another view, then the view bag data error occurs. (Because when I moved to another controller, the view bag method is on the HomeController Index Action. So then the View bag Data become null.)

So then I load the data to the session. So on the layout page, I called the session data as

 @{
     List<SelectListItem> MyBranch = Session["MyBranch"] as List<SelectListItem>;
   }

and the dropdown menu

 @Html.DropDownList(MyBranch, null, new { @class = "form-control js-dropdown js-MyBranch", @Id = "Branch" })

MyBranch has an error . Cannot convert selectListItem to string.

I cant use DropDownListFor because this has no model to assign the session data.

Is there any way of doing this?

CodePudding user response:

Replace Your code in view like below:

SelectList MyBranch = Session["MyBranch"] as SelectList;

@Html.DropDownList("MyBranch", MyBranch, new { @class = "form-control js-dropdown js-MyBranch", @Id = "Branch" })

You should pass MyBranch as selectlist in dropdownlist I wish that helps!

  • Related