I want to pass data from controller to view. In my Dinner control, I have a Edit action. The code is
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
ViewData["Countries"] = new SelectList(PhoneValidator.AllCountries, dinner.Country);
return View(dinner);
}
Then, I want to use a dropdown list to display countries's information in Edit view page. My code is
<div class="editor-label">
@Html.EditorFor(model => model.Country)
</div>
<div class="editor-field">
@Html.DropDownList("Country", ViewData["Countries"] as SelectList)
@Html.ValidationMessageFor(model => model.Country)
</div>
Then, I get an error in this line
@Html.DropDownList("Country", ViewData["Countries"] as SelectList)
The error information is
The ViewData item that has the key 'Country' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'
Note:
I have a class name DinnerViolation, I this class, I have a get method to retrive allcontries which I used in my Edit controller to set the value of SelectList, please check the code:
public class PhoneValidator
{
static IDictionary<string, Regex> countryRegex = new Dictionary<string, Regex>() {
{ "USA", new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}$")},
{ "UK", new Regex("(^1300\\d{6}$)|(^1800|1900|1902\\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\\d{4}$)|(^04\\d{2,3}\\d{6}$)")},
{ "Netherlands", new Regex("(^\\+[0-9]{2}|^\\+[0-9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-\\s]{10}$)")},
};
public static bool IsValidNumber(string phoneNumber, string country)
{
if (country != null && countryRegex.ContainsKey(country))
return countryRegex[country].IsMatch(phoneNumber);
else
return false;
}
public static IEnumerable<string> AllCountries
{
get
{
return countryRegex.Keys;
}
}
}
}
Any helps?Thanks
You are returning an IEnumerable<string>
public static IEnumerable<string> AllCountries
{
get
{
return countryRegex.Keys;
}
}
When you need to return an IEnumerable<SelectListItem>
Something like this (not tested):
public static IEnumerable<SelectListItem> AllCountries
{
get
{
var countries = new List<SelectListItem>();
foreach(var country in countryRegex.Keys)
{
countries.Add(SelectListItem() { Text = country, Value = country };
}
return countries;
}
}