[RESOLVED]MVC SelectList not setting the default value

So I am building a View to edit a record but I want to have drop downs. I am trying to show an Inventory record that has an Installer that installed that piece of inventory. But I want that installer to be selected in the drop down list if there is a value
for it. But currently it does not. Here is my controller for the SelectList:

private void SearchInstallerViewBag(int Installer = 0)
{
if (Installer == 0)

ViewBag.Installer = new SelectList(new[] {
new {id=-1, name="— Any —"}}.Union(_db.Installers.Select(
o => new { id = o.InstallerID, name = o.Name })), "id", "name", -1);

else

ViewBag.Installer = new SelectList(_db.Installers, "InstallerID", "Name", Installer);

}

public ActionResult EditInventory(int? projectinventoryid = null, int? installer = null)
{

if (projectinventoryid == null)
{
var model1 = _db.ProjectInventories.Where(e => e.ProjectInventoryID == 1).Single(); ;
SearchProjectViewBag(model1.ProjectName);

if (model1.Installer.HasValue)
{
SearchInstallerViewBag(model1.Installer.Value);
//SetInstallerViewBag(model1.Installer.Value);
}

return PartialView(model1);
}

var model = _db.ProjectInventories.Where(e => e.ProjectInventoryID == projectinventoryid).Single();
SearchProjectViewBag(model.ProjectName);

if (model.Installer.HasValue)
{
SearchInstallerViewBag(model.Installer.Value);
// SetInstallerViewBag(model.Installer.Value);
}
else
{
SearchInstallerViewBag();
// SetInstallerViewBag();
}
return PartialView(model);
}

Here is the part of the View for this Drop Down List:

@Html.DropDownList("Installer", (SelectList)ViewBag.Installer)
@Html.ValidationMessageFor(model => model.Installer)

Thanks,

Save the Installer on Hidden Filed , or TextBox to see the value is coming to the client side or not, if comes the use the hidden filed to store the value and assign it in the dropdown list ,, u can use jquery to bind the dropdown

Hi NEG1934,

Base on your code, the dropdownlist name is the same as the key of ViewBag.

Please use the different key of ViewBag.

private void SearchInstallerViewBag(int Installer = 0)
 {
 if (Installer == 0)

ViewBag.InstallerData = new SelectList(new[] { 
 new {id=-1, name="--- Any ---"}}.Union(_db.Installers.Select(
 o => new { id = o.InstallerID, name = o.Name })), "id", "name", -1);

else



ViewBag.InstallerData = new SelectList(_db.Installers, "InstallerID", "Name", Installer);

}
@Html.DropDownList("Installer", (SelectList)ViewBag.InstallerData)

Best Regards

Starain

Such a simple answer, I love those types of answers. Thank you very much. 

Leave a Reply