c# - How to post only the selected value from a DropDownList? -


with following setup below, nationalities posted server, don't care entire list, selected value. how modify code selected nationality posted rest of model?

model:

    // searchcriteria model public class searchcriteria() {     public searchcriteria()     {         nationalities = new list<selectlistitem>();         nationalities.add(new selectlistitem { text = "any nationality", value = "any nationality", selected = true });         nationalities.add(new selectlistitem { text = "united states", value = "united states", selected = false });         nationalities.add(new selectlistitem { text = "japanese", value = "japanese", selected = false });         nationalities.add(new selectlistitem { text = "mexican", value = "mexican", selected = false });         nationalities.add(new selectlistitem { text = "canadidan", value = "canadidan", selected = false });         nationalities.add(new selectlistitem { text = "chinese", value = "chinese", selected = false });     }     public string name {get;set;}     public string nationality { get; set; }     public list<selectlistitem> nationalities { get; set; } } 

controller:

    [httppost]     public actionresult find(searchcriteria model)     {                                        try         {             // find             return view(model);         }         catch         {             return view(model);         }     } 

view:

@html.label("name:"); @html.textboxfor(model => model.name); @html.label("nationality:"); @html.dropdownlistfor(model => model.nationality, model.nationalities); 

i think see problem. , it's not problem per se. it's misunderstanding on part.

the list of nationalities not posted controller. created constructor each time searchcriteria object created (including when model bound on post). not posted client server.

while work being done not necessary, it's not problem. actual posted value should in nationality member of searchcriteria object.

if not want nationalities object created each time, need move helper class , call when want populate data, or move out of class entirely , in controller. maybe better choice move data database.

by way, might want remove first item , make default text instead, parameter of dropdownlist/dropdownlistfor object.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -