dyarosh
asked on
Default value is not being set in my SelectList in MVC4 View
I have a View that displays a dropdown using the following in my view:
My Controller has the following code:
The CreateServerTypeSelectList is defined as follows:
I verified after the list is created that the SelectedValue is 2 which is the same value as the databaseServerTypeID in my model. (see attached picture)
My view has the following code for displaying the dropdown:
I verified that the list in the ViewBag still has the SelectedValue set to 2 and it does (see attached picture).
I've reviewed other posts and it seems like I am doing everything correctly but I can't get the default value to be selected. Any help is greatly appreciated!
CreateServerTypeSelectList.fw.png
CreateServerTypeSelectListinView.png
@Html.DropDownListFor(model => model.databaseServerTypeID, (SelectList)@ViewBag.databaseServerTypeID, "-- Choose Server Type --")
My Controller has the following code:
BusinessLogic bl = new BusinessLogic();
SelectList slServerType = bl.CreateServerTypeSelectList(_repository, appcatalog_database.databaseServerTypeID);
ViewBag.databaseServerTypeID = slServerType;
return View(appcatalog_database);
The CreateServerTypeSelectList
public SelectList CreateServerTypeSelectList(IAppCatalogContainerRepository repository, int defaultServerType)
{
IEnumerable<AppCatalog_ServerType> db;
db = repository.GetAllServerTypes();
SelectList sl;
if (defaultServerType == 0)
sl = new SelectList(db, "servertypeID", "servertypeName");
else
sl = new SelectList(db, "servertypeID", "servertypeName", defaultServerType);
return sl;
}
I verified after the list is created that the SelectedValue is 2 which is the same value as the databaseServerTypeID in my model. (see attached picture)
My view has the following code for displaying the dropdown:
<div class="editor-field">
@Html.Label("Server Type", new { @class = "editor-label" }) :
@Html.DropDownListFor(model => model.databaseServerTypeID, (SelectList)@ViewBag.databaseServerTypeID, "-- Choose Server Type --")
<span class="error-msg">@Html.ValidationMessageFor(model => model.databaseServerTypeID)</span>
</div>
I verified that the list in the ViewBag still has the SelectedValue set to 2 and it does (see attached picture).
I've reviewed other posts and it seems like I am doing everything correctly but I can't get the default value to be selected. Any help is greatly appreciated!
CreateServerTypeSelectList.fw.png
CreateServerTypeSelectListinView.png
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I had not received any help from the Experts in a while so I kept trying different things until I finally got it to work.
I prefer the strong-typed ViewModel over the dynamic ViewBag.
Here is an article that talks about the ViewModel:
Part 3: Views and ViewModels
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-3