在DropDownList中的MVC3设置默认选定值 [英] Setting a default selected value in DropDownList in MVC3

查看:120
本文介绍了在DropDownList中的MVC3设置默认选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC3我有我的控制器此code。它检索的ID \\名称从安装表列表,并创建一个ViewBag

In MVC3 I have this code at my controller. It retrieves a List of IDs\Names from Installation table and creates a ViewBag

var vs = dba.Installation.OrderBy(q => q.InstName).ToList();
ViewBag.Vessels = new SelectList(vs, "InstId", "InstName");

现在,在我的看法。我想呈现一个下拉列表清单。我使用的HTML帮助工作正常...

Now, at my view. I want to render the list in a dropdown list. I used the Html helper that works fine...

@Html.DropDownList("InstId",(SelectList)ViewBag.Vessels, "- Select one -")

我需要设置第一个项目在ViewBag列表作为默认选择的值,而不是 - 请选择 - 文本。

I need to set first item in the ViewBag List as a default selected value, instead of "- Select one -" text.

我该怎么办呢?

在此先感谢!

推荐答案

有对的SelectList 构造函数4个参数的重载。其中最后是默认选择的对象。例如:

There's an overload for the SelectList constructor that takes 4 arguments. The last of which is the default selected object. E.g:

ViewBag.Vessels = new SelectList(vs, "InstId", "InstName", selectedValue);

其中,了selectedValue 是什么类型列表中的一个对象。

Where selectedValue is an object of whatever type is in your list.

这篇关于在DropDownList中的MVC3设置默认选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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