Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

c# - Set selected value in SelectList after instantiation

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are fighting the framework. The data going into your views should be created at the Last Possible Minute (LPM).

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.

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

These SelectLists all use the Countries list of type List<Country>.

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);
    }
}

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...