消费来自不同类mvc的选择列表

时间:2013-08-08 20:10:57

标签: asp.net-mvc razor html-select

我试图让我的代码更具可读性。 这是一个我正在使用硬编码的MVC项目

 ViewBag.Origin = new List<SelectListItem>
                        {
                            new SelectListItem { Text = "Born", Value = "Born"},
                            new SelectListItem { Text = "Donated", Value = "Donated"},
                            new SelectListItem { Text = "Bought", Value = "Bought"}
                        }; 

在应用程序中有很多时间,所以我决定将其移入存储库类。

public class Repository
{

    public List<SelectListItem> GetOriginList()
    {
        List<SelectListItem> originItems = new List<SelectListItem>
                    {
                        new SelectListItem { Text = "Born", Value = "Born"},
                        new SelectListItem { Text = "Donated", Value = "Donated"},
                        new SelectListItem { Text = "Bought", Value = "Bought"}
                    };

        return originItems;
    }

然后尝试访问它。

public class CowController : Controller
{
    Repository repository = new Repository();

    ActionResult Create() {
     ViewBag.origin = repository.GetOriginList();
    return View();

    }
}

我的观点

@ Html.DropDownList(“Origin”,“Select Origin”)

但它查看我的运行时错误。

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The ViewData item that has the key 'Origin' is of type 'System.Collections.Generic.List`1[[System.Web.WebPages.Html.SelectListItem, System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]' but must be of type 'IEnumerable<SelectListItem>'.

仅在操作上进行硬编码时工作正常。 我忘了任何类型转换?

2 个答案:

答案 0 :(得分:3)

当我使用System.Web.WebPages.Html替换时工作; 使用System.Web.Mvc。

我不知道技术差异..但如果你有同样的问题,你可以尝试我的解决方案...... 如果有人可以用技术差异发表评论,那将会很棒......

当我加入两个参考文献时的另一个要点。

Error   1   'SelectListItem' is an ambiguous reference between 'System.Web.WebPages.Html.SelectListItem' and 'System.Web.Mvc.SelectListItem'

答案 1 :(得分:0)

那里有一个错误,来自 origin 的情况。 ViewBag使用dynamic类型,然后这不会在编译时抛出任何错误,但在运行时会出现错误。

ViewBag.origin = repository.GetOriginList();

但你调用了DropDownList

@Html.DropDownList("Origin", "Select Origin")

区分大小写,你应该改变

ViewBag.origin to  ViewBag.Origin

或称之为:

@Html.DropDownList("origin ", "Select Origin")

编辑:

也改变存储库功能:

 public IEnumerable<SelectListItem> GetOriginList()