2013-06-05 32 views
1

我想将数据从控制器传递到查看。在我的晚餐控制中,我有一个编辑操作。代码是ViewData错误 - 使用ViewData将数据从控制器传递到查看

// 
// 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); 
} 

然后,我想使用下拉列表在编辑视图页面中显示国家的信息。我的代码是

<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> 

然后,我在这条线得到一个错误

@Html.DropDownList("Country", ViewData["Countries"] as SelectList) 

错误信息是

The ViewData item that has the key 'Country' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>' 

注:

  • 我有一个“国家“的财产在我的餐桌上。国家类型是字符串。
  • 我认为错误行中的“国家”只是定义了显示名称 该字段的形式。所以错误似乎inresonabel。
  • 我有一个类名DinnerViolation,我这个班,我有一种渴望 方法以检索,我在我的编辑控制器,用于设置的SelectList的价值allcontries,请检查代码:

    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; 
          } 
         } 
    
        } 
    

    }

任何帮助?谢谢

+2

开始使用视图模型,并退出与'ViewData'和'ViewBag'乱搞。 – gdoron

回答

0

您正在返回一个IEnumerable<string>

public static IEnumerable<string> AllCountries 
{ 
    get 
    { 
     return countryRegex.Keys; 
    } 
} 

当你需要返回IEnumerable<SelectListItem>

像这样(未测试):

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; 
    } 
} 
+0

感谢您的所有答案。最后,我使用ViewModel作为gdoron建议。我的问题解决了。 Tom Studee,我选择了你的答案,因为我认为你对我的代码付出了努力。谢谢。 – Lucky

相关问题