0

我正在尝试使我的代码更具可读性。这是一个 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>'.

仅对动作进行硬编码时工作正常。我忘记了任何类型转换吗?

4

2 回答 2

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'
于 2013-08-09T11:49:38.947 回答
0

Theres an error there, the case from origin. ViewBag uses dynamic types, then this will not throw any error in compilation time, but in runtime if something is wrong.

ViewBag.origin = repository.GetOriginList();

But you calling the DropDownList

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

Its case sensitive, you should change

ViewBag.origin to  ViewBag.Origin

or call it:

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

EDIT:

Change the Repository function too:

 public IEnumerable<SelectListItem> GetOriginList()
于 2013-08-08T20:33:39.753 回答