Reputation: 702
I have this ViewModel :
public class FoundViewModel
{
public string Title { get; set; }
public string Description { get; set; }
public int City { get; set; }
public int SubGroup { get; set; }
public string Address { get; set; }
public DateTime FindDate { get; set; }
}
and in View I add two Dropdown and Fill it in actionresult when call get:
var Provinces = _provinces.SelectAll();
ViewBag.Provinces = new SelectList(Provinces,"Id","Title",Provinces.FirstOrDefault().Id);
and in view :
@Html.DropDownList("drpProvince", (SelectList)ViewBag.Provinces, new { @onchange="javascript:getcity(this.value);"})
But when Click on the button and post it , I getting this ERROR:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'drpProvince'
I found some similar question on stackover flow but can't know .
What's a Problem ? thanks.
Upvotes: 0
Views: 58
Reputation: 1497
This Error Occured when you fill viewbag in Get
View and when it post and Model is not Valid , You Returned model to the View And viewBag is null, You should be Fill all Viewbag if Model is not Valid befor return view.
[Httppost]
public ActionResult YouAction(myVm mymodel)
{
if (!ModelState.IsValid)
{
// fill your Viewbags
return View(mymodel);
}
}
Upvotes: 1
Reputation: 348
What happens is that, at the time of the post and reload the page to show the cities according to the selected province, are not generating ViewBag again.
The solution is to initialize the ViewBag again since this is lost after PostBack each call.
Example.
public ActionResult loadCities () {
/* Logic .... */
// Here initialize ViewBag again to view the know.
return View ();
}
Upvotes: 3