Tuesday, June 9, 2009

ASP.NET MVC Dropdownlist Values on Server

I wanted to get the values directly from the dropdownlist on the server. For example, I wanted to make a drop down list, and when the user chose either one or multiple values, make a query on the server based on those values.

Well, you can't just write the "select" tag html and expect to get those values on the server. If you want to directly write the html tag, I had to make hidden fields, when the user chose a value in the dropdownlist, make the hidden field's value the value of the dropdownlist.

Well, there is a way. Use the html helper for a dropdownlist.

Before making the dropdownlist, make a dictionary of KeyValuePairs and Values.

The KeyValuePairs are the Key and Values, and the Values are just the values.

You can just make a dictionary and have just the key and values. This will work if you just need the keys on the server side.


The KeyValuePair is just if you want both the key and value on the server. If not, then just make a dictionary of string,string. Where the "new SelectList(d, 'Key', 'Value')" shows, the Key is what is sent to the server, and the value is what is shown to the user. You can change "Key" to "Value" and the value will be sent.

On the server side, you should have a List[string] Name as the variable to receive the data. It can be just "string" but you will only get the first selected key if multple are selected, where the list makes it possible to get all selected keys. If you send back a KeyValuePair as a key, then the values will look like "[key,value]".

No comments:

Post a Comment