I suggest some changes in your solution:
Instead of DropDownListFor()
use just DropDownList()
@Html.DropDownList("CultureCode", new SelectList(db.CultureCodes, "ID", "DisplayName"))
Instead of accessing your database data in your view... which is very out of the standard and you are coupling the Views (usually HTML) with the database... you should put the query in your controller and put the data in the ViewBag collection.
So, in your Layout, instead of the code I suggested above, you should use:
@Html.DropDownList("CultureCode", (SelectList)ViewBag.Codes, "Select one...")
In your controller you load it as follow:
ViewBag.Codes = new SelectList(db.CultureCodes, "ID", "DisplayName");
EDIT:
You can do an action filter, to load or inject the CultureCodes
in the ViewBag
:
public class IncludeCultureCodesAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.Controller;
// IController is not necessarily a Controller
if (controller != null)
{
var db = new YourContext();
controller.ViewBag.Codes = new SelectList(db.CultureCodes, "ID", "DisplayName"));;
}
}
}
Then, in your Controller actions... you can decorate them with [IncludeCultureCodes]
. So, the action with that attribute will load the collection of codes.
But I think is a better approach to load one time the layout (on Home/Index for example) and then use partial views. This way you only reload the layout going back to home... or other full view calls.