MVC:填充的最佳方法的Html .DropDownList [英] MVC: Best way to populate Html .DropDownList

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

问题描述

我在寻找一个使动态数据到视图来填充一个DropDownList健全的哲学。难道是一个好主意,创造dropdownlists等架空的数据模型对象或使用viewbag?

I'm looking for a sound philosophy for bringing dynamic data into a view to populate a dropdownlist. Would it be a good idea to create a model object for dropdownlists and other "overhead" data or use a viewbag?

感谢

推荐答案

使用ViewBag(如一些在其他的答案/意见建议)从你的控制器,查看获得的数据通常被视为一个code缺乏。

Using the ViewBag (as some have suggested in other answers/comments) to get data from your controller to view is generally seen as a code lack.

您的视图模型最好应该包含所有你需要为你的视图中的数据的。因此,使用您的控制器来填充你的视图模型的属性这样的数据:

下面是如何使用Html.DropDownListFor使用模型来创建ASP.NET MVC下拉列表一个简单的例子。
你可以像下面这样做的所有内联在你的* .cshtml文件,像这样:

Here is a simple example of how to create a drop down list in ASP.NET MVC using Html.DropDownListFor using model. You can do it like this all inlined in your *.cshtml file like so:

@Html.DropDownListFor(model => model.Package.State, new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Red"  },
                       new { value = 1 , text = "Blue" },
                       new { value = 2 , text = "Green"}
                    },
                  "value",
                  "text",
                   2))

这将创造这样的:

which will create like this:

<select id="Package_State" name="Package.State"><option value="0">Red</option>
<option value="1">Blue</option>
<option value="2">Green</option>
</select>

请参照<一个href=\"http://stackoverflow.com/questions/19876604/populate-dropdownlist-using-mvc-4-entity-framework\">this回答了解详情

这篇关于MVC:填充的最佳方法的Html .DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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