【问题标题】:ViewData Error-Using ViewData passes data from controller to viewViewData 错误-使用 ViewData 将数据从控制器传递到视图
【发布时间】:2013-06-05 18:37:41
【问题描述】:

我想将数据从控制器传递到视图。在我的晚餐控件中,我有一个编辑操作。代码是

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

注意:

  • 我的餐桌上有一个“Country”属性。国家的类型是字符串。
  • 我认为错误行中的“国家”只是在 该字段的形式。所以这个错误似乎是不合理的。
  • 我有一个类名DinnerViolation,我这个类,我有一个get 检索我在编辑控制器中用于设置 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;
                }
            }
    
        }
    

    }

有什么帮助吗?谢谢

【问题讨论】:

  • 开始使用 ViewModel 并停止使用 ViewDataViewBag

标签: c# asp.net viewdata


【解决方案1】:

您返回的是IEnumerable&lt;string&gt;

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

当您需要返回IEnumerable&lt;SelectListItem&gt;

类似这样的东西(未测试):

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

【讨论】:

  • 感谢您的所有回答。最后,我按照 gdoron 的建议使用 ViewModel。我的问题解决了。 Tom Stude,我选择了你的答案,因为我认为你在我的代码上付出了努力。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-11-09
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多