Пожалуйста, измените действие вашего контроллера как:
public ActionResult Add()
{
List<Location> listObj = LocDrpDwnList();
/*
// Doesn't hurt populating SelectListItem this way. But you don't need to do this here.
List<SelectListItem> LocList = new List<SelectListItem>();
foreach (var item in listObj)
{
LocList.Add(new SelectListItem
{
Text = item.LocationName.ToString(),
Value = Convert.ToInt32(item.LocID).ToString()
});
}
*/
ViewBag.LocID = (string?)null; //Set to some predefined locId selection, so when page is loaded, dropdown will be defaulted to this value.
ViewBag.LocList = LocList;
return View();
}
, а затем обновите свой вид как:
@{
var LocList = new SelectList(ViewBag.LocList, "Id", "Text");
string LocId = ViewBag.LocId ?? (string)null;
}
@Html.DropDownList(@LocId, @LocList , "Select Location", new { htmlAttributes = new { @class = "form-control" } })
Вместо использования ViewBags рекомендуется использовать ViewModels, как показано ниже:
public class AddViewModel
{
public AddViewModel()
{
this.LocList = new List<LocationViewModel>();
}
public int? LocId { get; set; }
// Instead of LocationViewModel, you can go with your idea List<SelectListItem> and change controller action and view accordingly.
public List<LocationViewModel> LocList { get; set; }
}
public class LocationViewModel
{
public int LocId { get; set; }
public string LocationName { get; set; }
}
и ваше действие контроллера будет:
public ActionResult Add()
{
List<Location> listObj = LocDrpDwnList();
List<LocationViewModel> LocList = new List<LocationViewModel>();
foreach (var item in listObj)
{
LocList.Add(new LocationViewModel
{
LocationName = item.LocationName.ToString(),
LocId = Convert.ToInt32(item.LocID).ToString()
});
}
/*
ViewBag.LocID = (string?)null; //Set to some predefined locId selection, so when page is loaded, dropdown will be defaulted to this value.
ViewBag.LocList = LocList;*/
return View(new AddViewModel{LocList = LocList});
}
, и ваше представление будет;
@using AddViewModel
@Html.DropDownList(m => m.LocId, new SelectList(Model.@LocList, "Id", "Text") , "Select Location", new { htmlAttributes = new { @class = "form-control" } })