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'.
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
HttpGet
, one for HttpPost
. Could you update the answer with the HttpPost
action - Ethan Brown 2012-04-11 22:48
HttpGet
is the default option if you don't specify it - Ethan Brown 2012-04-11 22:58
ViewBag.gov
in your HttpPost
action. So when you return View()
, it isn't available, which is why you're getting that error. Set ViewBag.gov
in your HttpPost
action, and that should clear that error - Ethan Brown 2012-04-11 23:00