1

The values in formcollection object are stored as Key-value pairs. But, suppose somebody uses "Id" as the value and "Name" as the text to populate a dropdownlist. In that case, how can one access "Name" from the dropdownlist using formcollection object?

To access the selected value, I know this code:

public ActionResult ActionName(FormCollection formcollection)
{
   var value = formcollection["dropdownlistName"];
}

The above code will give the value which is "Id", but what if I need to retrieve "Name" and store it in a variable?

I am a novice; if somebody knows, please help. Your help will be appreciated. Thanks.

1 Answer 1

1

You cannot post the drop down list text to the server, you can only sent the values. There are workarounds -- you can POST the data manually and add the dropdown text along with it. But the proper way to do it is to refer back the id from the source you filled the drop down list in the first place.

Example:

If you have a drop down like this:

<form id="someForm">
<select id="country" name="countryddl">
    <option value="1">US</option>
    <option value="2">UK</option>
</select>
<input type="submit" value="submit"/>
</form>

Get the value in the controller and map it back to the source.

public ActionResult ActionName(FormCollection formcollection)
{
   var countryId = formcollection["countryddl"];
   var countryName = countriesMap[countryId ]; // Assuming countriesMap is a dictionary with all countries mapped to its Id.

}

Workaround

If you absolutely must send the text along in the form, you can override the default behaviour on form submitting and post the dropdown text along with the value:

$("#btnSubmit").click(function(e){
    e.preventDefault();

    var selectedOption = $("#CountryId option:selected").text();
    // Add the selected drop down text to a hidden field
    $("<input/>",{type:'hidden',name:'countryName'}).val(selectedOption).appendTo("#someForm");
    // now post the form 
    $("#someForm").submit();
});

Now you can get the selected text in your controller like this:

var countryName = formcollection["countryName"];
Sign up to request clarification or add additional context in comments.

1 Comment

Is the workaround a less desirable method of doing this? If so, why?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.