Reputation: 301
I have filled the ViewBag.BankNames using Banks table as
ViewBag.BankNames = new SelectList(db.Banks, "BankId", "BankName", applicationSettings.BankId);
where applicationSettings.BankdId is having the value which I need to show as the selected value in dropdown, then passed the applicationSetting model object to view.
In my View I have used that ViewBag like
@Html.DropDownListFor(model => model.BankId, ViewBag.BankNames as SelectList, "Select Bank", htmlAttributes: new { @class = "form-control" })
It will show me the dropdown list with all values of Bank names but the selected value is Select Bank and not the value which I set as selected value in ViewBag?
Upvotes: 0
Views: 491
Reputation: 81
Can you assign applicationSettings.BankId to BankId of model property and check..
you are binding @Html.DropDownListFor(model => model.BankId, ViewBag.BankNames as SelectList, "Select Bank", htmlAttributes: new { @class = "form-control" }) but in model.BankId is zero..
Assign Model.BankId = applicationSettings.BankId before returning it to view
In Controller
public ActionResult Index()
{
var banks = new List<Banks>()
{
new Banks()
{
BankId =1,
BankName = "Bank 1"
},
new Banks()
{
BankId =2,
BankName = "Bank 2"
}
};
var list = new SelectList(banks, "BankId", "BankName");
ViewBag.Banks = list;
var modelBanks= new Banks();
modelBanks.BankId = 2;
return View(modelBanks);
}
In View
@model Banks
@using WebApplication3.Models
@Html.DropDownListFor(model => model.BankId, ViewBag.Banks as SelectList,"Select Bank")
Upvotes: 1