MVC3 DropDownList用于不填充selectedValue [英] MVC3 DropDownListFor not populating selectedValue

查看:57
本文介绍了MVC3 DropDownList用于不填充selectedValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我正在服用疯狂药丸.我有一个下拉列表,用于从数据库中读取我们拥有的所有葡萄酒生产商的视图.我想将selectedValue设置为引用页面驱动的特定ID.我可以看到它在调试中拾取了selectedValue,我看到了填充的选定值(本例中为906),但是在呈现页面时,它没有将dropdownlist设置为正确的值,默认情况下它始终默认为1价值.我尝试在剃刀中创建selectList而不是我的控制器,但是没有任何效果.在这方面的任何帮助,将不胜感激,我猜它很小.

I feel like I'm taking crazy pills. I have a dropdownlist for a view that reads from our database all of the wine producers we have. I want to set the selectedValue to a particular ID driven by the referring page. I can see it picks up the selectedValue in debug, I see the selected value populated (906 for this example), but it doesn't set the dropdownlist to the correct value when the page is rendered, it always defaults to 1 for the default value. I've tried creating the selectList in razor as opposed to my controller, but nothing works. Any help on this would be appreciated, I'm guessing it is something small.

控制器:

        if (User.IsInRole("admin"))
        {
            if (ID != 0)
            {
                ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name", ID);
            }
            else
            {
                ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name");
            }
        }

查看:

if (User.IsInRole("producereditor"))
{
    <h3>@ViewBag.ProducerName</h3>
}
    else
{
<div class="editor-label">
    @Html.LabelFor(m => m.Wine.ProducerID, "Producer")
</div>
<div class="editor-field">
    @Html.DropDownListFor(m => m.Wine.ProducerID, ViewBag.ProducerSelect as SelectList)
</div>
}

尝试以下方法,但没有成功:

Tried the below but no success:

         ViewBag.ProducerSelect = new SelectList(from p in db.Producers
                                                    orderby p.Name
                                                    select new { p.ProducerID, p.Name }
                                                    , "ProducerID", "Name", ID);

推荐答案

我知道了.我在页面上其他地方的隐藏字段中使用了ViewModel.wine.ProducerID,它的默认值为1,因此我将其分配给传入的值,并且效果很好.我知道那是那样的.谢谢!

I figured this out. I had ViewModel.wine.ProducerID elsewhere on the page in a hidden field, and that defaults to 1, so I just assigned that to passed in value, and it worked great. I knew it was something like that. Thanks!

这篇关于MVC3 DropDownList用于不填充selectedValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆