Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading