I have an ASP.NET MVC project with entities based on EF6 (model first). So my entities are all auto-generated for me. I have an entity, Site
and I just want the user to select a Site
before proceeding. I have tried a couple of ways, all of them work, but they seem very messy and unnecessary.
I was curious about the cleanest way to create a DropdownList
of Site
s, then get the selected site when the form is submitted (by Id
or whatever other mechanism is better).
Currently I have:
The index where the user is asked to select a site:
public ActionResult Index()
{
ViewBag.Sites = new SelectList(db.Sites.ToList(), "Id", "Name");
return View();
}
The view:
@using (Html.BeginForm("SetSite", "Home"))
{
@Html.Label("sites", "Site:");
@Html.DropDownList("Sites", null, new { @class = "selectpicker" });
<div style="width:100%;height:25px"></div>
<button class="btn btn-default" style="width:100%">Go</button>
}
And the SetSite
action, where the form is submitted
[HttpPost]
public ActionResult SetSite()
{
if (Request.Form["Sites"] != null)
{
Session["Site"] = db.Sites.Find(Request.Form["Sites"]);
return RedirectToAction("Home");
}
else
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
A few problems arise from this method. First, I really wanted to take advantage of the @model
functionality in razor and point it towards my Site
class, but since it's auto-generated, I don't want to go poking around and adding a whole bunch of view properties. (beggars can't be choosers?)
Second, the Request.Form['Sites']
returns a string, and converting it to and int is ugly as hell.
As I mentioned, I'd like to use the @model
functionality with Html.DropDownListFor
. Is that possible when working with a list of Sites
from the DB?
How can I get this done cleanly?