在 ASP.NET MVC 2 中实现 DropDownList 的最佳方式? [英] Best way of implementing DropDownList in ASP.NET MVC 2?

查看:24
本文介绍了在 ASP.NET MVC 2 中实现 DropDownList 的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解使用 DropDownListFor 帮助程序在 ASP.NET MVC 2 中实现 DropDownList 的最佳方式.这是一个多部分的问题.

I am trying to understand the best way of implementing a DropDownList in ASP.NET MVC 2 using the DropDownListFor helper. This is a multi-part question.

首先,将列表数据传递给视图的最佳方式是什么?

First, what is the best way to pass the list data to the view?

  1. 使用包含数据的 SelectList 属性在模型中传递列表
  2. 通过ViewData
  3. 传入列表
  1. Pass the list in your model with a SelectList property that contains the data
  2. Pass the list in via ViewData

如何在 DropDownList 中获得空白值?我应该在创建它时将它构建到 SelectList 中,还是有其他方法可以告诉助手自动创建一个空值?

How do I get a blank value in the DropDownList? Should I build it into the SelectList when I am creating it or is there some other means to tell the helper to auto create an empty value?

最后,如果由于某种原因出现服务器端错误并且我需要使用 DropDownList 重新显示屏幕,我是否需要再次获取列表值以传递到视图模型中?这些数据不在帖子之间维护(至少当我通过我的视图模型传递它时不会),所以我打算再次获取它(它被缓存).我的做法正确吗?

Lastly, if for some reason there is a server side error and I need to redisplay the screen with the DropDownList, do I need to fetch the list values again to pass into the view model? This data is not maintained between posts (at least not when I pass it via my view model) so I was going to just fetch it again (it's cached). Am I going about this correctly?

推荐答案

你最好的办法是在你的控制器中创建一个 SelectList - 在这里使用我的扩展方法:http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc

Your best bet is to create a SelectList in your Controller - use my extension method here: http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc

使用与您的属性名称相同的键将其弹出到 ViewData 中:ViewData["statusid"]=MySelectList

Pop that into ViewData using the same key as your property name: ViewData["statusid"]=MySelectList

然后只需使用 Html.DropDownFor(x=>x.StatusID) 就可以了.

Then just use Html.DropDownFor(x=>x.StatusID) and you're all set.

这篇关于在 ASP.NET MVC 2 中实现 DropDownList 的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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