实例化后的SelectList设置选定值 [英] Set selected value in SelectList after instantiation
问题描述
我说得对认为有没有办法在创建后设置在C#类的SelectList所选择的价值? 是不是有点傻?
Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created? Isn't that a bit silly?
推荐答案
我觉得你是战斗的框架。数据进入你的意见,应在最后一分钟(LPM)创建。
I think you are fighting the framework. The data going into your views should be created at the Last Possible Minute (LPM).
这样的想法,一个的SelectList
是一种喂的DropDownList
HTML帮手。这是不是在你决定如何处理它来存储数据的地方。
Thinking this way, a SelectList
is a type to feed the DropDownList
HTML helper. It is NOT a place to store data while you decide how to process it.
有一个更好的解决办法是检索数据成名单,其中,T>
然后初始化的SelectList
( S),当您需要。这种做法的一个直接的好处是,它可以让你重用你的名单,其中,T>
的多个的DropDownList
,如:
A better solution would be to retrieve your data into a List<T>
and then initialize the SelectList
(s) when you need to. An immediate benefit of this practice is that it allows you to reuse your List<T>
for more than one DropDownList
, such as:
Country of birth
Country of residence
这些 SelectLists
全部使用类型的国家名单名单,其中,国家&GT;
These SelectLists
all use the Countries list of type List<Country>
.
您可以使用名单,其中,T&GT;
在最后一分钟就像这个例子:
You can use your List<T>
at the 'last minute' like in this example:
public class TaxCheatsFormViewModel
{
private List<Country> countries { get; set; }
public TaxCheat Cheat { get; private set; }
public SelectList CountryOfBirth { get; private set; }
public SelectList CountryOfResidence { get; private set; }
public SelectList CountryOfDomicile { get; private set; }
public TaxCheatsFormViewModel(TaxCheat baddie)
{
TaxCheat = baddie;
countries = TaxCheatRepository.GetList<Country>();
CountryOfBirth = new SelectList(countries, baddie.COB);
CountryOfResidence = new SelectList(countries, baddie.COR);
CountryOfDomicile = new SelectList(countries, baddie.COD);
}
}
关键是,你应该让你的数据在名单,其中,T&GT;
,直到你真正需要它输出;最后一分钟(LPM)。
The point being that you should keep your data in a List<T>
till you really need to output it; the last possible minute (LPM).
这篇关于实例化后的SelectList设置选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!