Reputation: 3110
This is my DropdownList :
<div class="editor-label">
<p>
<%: Html.LabelFor(model => model.Gov) %>
</p>
</div>
<div class="editor-field">
<p>
<%=Html.DropDownListFor(model => model.Gov, ViewBag.gov as SelectList)%>
<%: Html.ValidationMessageFor(model => model.Gov) %>
</p>
and this is my view controller :
public ActionResult TestR()
{
ViewBag.gov = new SelectList(entity.gouvernerat, "Idgov", "Nomg");
return View();
}
With HttpPost :
[HttpPost]
public ActionResult TestR(LogModel.preRegister Model)
{
if (ModelState.IsValid)
{
if (LogModel.preRegister.Verifuser(Model.IDag))
{
ModelState.AddModelError("", "Agence existe deja");
return View(Model);
}
else
{
int ins = LogModel.preRegister.Register(Model);
if (ins > 0)
{
return View("Index");
}
else return View();
}
}
else
{
return View();
}
}
Now Dropdown list show me the list of Gov in my DB(that's what i want), but when i clic on create i got this error in my DropdownLisrt There is no ViewData item of type 'IEnumerable <SelectListItem>' with key 'Gov'.
Upvotes: 1
Views: 4470
Reputation: 27282
This is pretty easy with LINQ to SQL. Let's say you have a table Govs
that contains your "Tunis", "Ariana", etc. strings. You can then create your select list like this:
govs.Select( x => new SelectListItem { Text = x.Name, Value = x.Name } );
Of course you can even be more flexible and assign the value to something else, like an ID.
Update: more details to answer questions posed in comments:
Add the select list items in the view model:
public IEnumerable<SelectListItem> GovItems { get; set; }
Then, in the controller, before returning your view:
// database code to get "Govs" table goes here....
var vm = new MyViewModel {
GovItems = govs.Select( x => new SelectListItem { Text = x.Name, Value = x.Name } );
}
Then in your view:
@Html.DropDownListFor( x => x.Gov, Model.Govs )
I hope this helps. If you're still confused, I recommend reading some tutorials about ASP.NET MVC. I recommend Microsoft's official one:
http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part1-cs
Upvotes: 2