Hmtl.DropDownList仅使用ViewBag作为选定值 [英] Hmtl.DropDownList using only ViewBag for selected value

查看:39
本文介绍了Hmtl.DropDownList仅使用ViewBag作为选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用ViewBag中的项目创建一个下拉列表,但是似乎没有选择当前项目的方法.我不是使用模型来实现此目的,只是想使用ViewBag,否则我将不得不创建另一个模型类来包装选择的项和要显示的实际数据.

I can create a dropdown list with items from the ViewBag, but there doesn't seem to be a way to select the current item. I'm not using the model to achieve this, just want to use ViewBag, otherwise I'd have to create another model class just to wrap the select items and the actual data to display.

我的代码:

@Html.DropDownList("MyFilter", (IEnumerable<SelectListItem>)ViewBag.SelectItems, "Show All" )

没有参数可以设置选择列表的值.我在俯视什么吗?如果我要使用DropDownListFor<>,这仅对模型有效吗?

There is no parameter to set the value of the select list. Am I overlooking something? If I were to use DropDownListFor<> does this only work against the model?

推荐答案

您可以尝试在 ViewBag/ViewData 中设置 MyFilter 属性:

You could try setting the MyFilter property in your ViewBag/ViewData:

public ActionResult Index()
{
    ViewBag.SelectItems = new[]
    {
        new SelectListItem { Value = "1", Text = "item 1" },
        new SelectListItem { Value = "2", Text = "item 2" },
        new SelectListItem { Value = "3", Text = "item 3" },
    };

    // preselect the second item
    ViewBag.MyFilter = "2";

    return View();
}

但是我的建议是使用视图模型和辅助程序的强类型版本:

But my recommendation is to use view models and the strongly typed version of the helper:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        SelectItems = new[]
        {
            new SelectListItem { Value = "1", Text = "item 1" },
            new SelectListItem { Value = "2", Text = "item 2" },
            new SelectListItem { Value = "3", Text = "item 3" },
        },
        // preselect the second item
        MyFilter = "2"
    };
    return View(model);
}

并在您的强类型视图中:

and in your strongly typed view:

@model MyViewModel
...
@Html.DropDownListFor(x => x.MyFilter, Model.SelectItems, "Show all")

这篇关于Hmtl.DropDownList仅使用ViewBag作为选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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