I have the following in my view:
<div class="editor-field">
@Html.DropDownListFor(x => x.Subject, (IEnumerable<SelectListItem>) ViewBag.Clients)
</div>
This is how I’m calling the View:
var list = new List<SelectListItem>
{
new SelectListItem {Text = "Gas Order", Value = "delivery"},
new SelectListItem {Text = "Account Services", Value = "account"},
new SelectListItem {Text = "Service Call", Value = "service"},
new SelectListItem {Text = "Inquiry", Value = "inquiry"}
};
ViewBag.Clients = list;
return View();
And this is in my model:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Text)]
[Display(Name = "Subject")]
public string Subject { get; set; }
I am trying to return back the selected value.
When I reload the screen due to an error on the screen, I am getting this error:
The ViewData item that has the key ‘Subject’ is of type
‘System.String’ but must be of type ‘IEnumerable’.
I’m assuming it is due to this line:
public string Subject { get; set; }
If that is the case, how do I get the selected item back to my model?
Make sure
ViewBag.Clientshas the right value on refresh.This is why you should avoid using
ViewBagand use only ViewModel.Put all the relevant data there.