简体   繁体   English

MVC2 DropDownListFor问题,仅显示类名

[英]Issue with MVC2 DropDownListFor, only displaying the class-name

Good day, 美好的一天,

I have this problem with Html.DropDownListFor which I can't seem to work out.. It gives me the correct number of options, if I do a breakpoint in the code where it is supposed to render the list, the "SelectItemList" object contains the items with correct values, but the actual HTML it spits out is the following: 我有Html.DropDownListFor这个问题我似乎无法解决..它给了我正确的选项数,如果我在代码中执行断点,它应该呈现列表,“SelectItemList”对象包含具有正确值的项目,但它吐出的实际HTML如下:

<select id="Reason_ReasonId" name="Reason.ReasonId"><option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>

The module containts this: 该模块包含:

public SelectList ReasonList
{
    get
    {
        SelectList selectList;
        List<SelectListItem> selectItems;

        using (var db = new EscalationDataContext())
        {
            var reasons =
                db.Reasons
                .OrderBy(r => r.Reason1)
                .Select(r => new SelectListItem
                {
                    Value = r.ReasonId.ToString(),
                    Text = r.Reason1
                });

            selectItems = reasons.ToList();

            selectList = new SelectList(selectItems);
        }

        return selectList;
    }
}

The controller just creates a default instantiation and sets the default value: 控制器只是创建一个默认实例,并设置默认值:

    public ActionResult Create()
    {
        EscalationModel model = new EscalationModel
        {
            Reason = new Reason { ReasonId = new Guid("598c28c2-877a-44fa-9834-3241c5ee9355"), Reason1 = "Taken too long" },
            ActionedDate = DateTime.Now
        };

        return View(model);
    } 

Last but not least, the view: 最后但同样重要的是,观点:

<%: Html.DropDownListFor(m => m.Reason.ReasonId, Model.ReasonList) %>

Any ideas why it behaves like this? 有什么想法,为什么它的行为像这样? As I said, in the actual code (in the view) I have the correct values, but.. It doesn't like me.. Any help would be greatly appreciated, thanks in advance! 正如我所说的,在实际代码中(在视图中)我有正确的值,但是..它不喜欢我..任何帮助都将非常感谢,提前感谢!

Ok.. It seems you had to specify which variable in SelectListItem was used for "Value" and which was used for "Text".. 好的..似乎你必须指定SelectListItem中的哪个变量用于“Value”并且用于“Text”..

selectList = new SelectList(selectItems);

Became.. 成为..

selectList = new SelectList(selectItems, "Value", "Text");

Which seems to have done the trick! 这似乎已经成功了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM