Home >Backend Development >C++ >How to Get the Selected Value from a DropDownList in an MVC Controller?
Get SelectedValue of dropdown list in MVC controller
In MVC applications, assigning values to drop-down lists from the database is a very common scenario. However, when you submit the form, you need to access the selected value in the controller. This article provides two methods to achieve this:
Method 1: Use Request or FormCollection
The first method reads the selected value directly from the request. Using Request.Form you can specify the key of the dropdown (ddlVendor in this case) to retrieve the posted value:
<code class="language-csharp">string strDDLValue = Request.Form["ddlVendor"].ToString();</code>
Alternatively, you can use FormCollection:
<code class="language-csharp">[HttpPost] public ActionResult ShowAllMobileDetails(MobileViewModel MV, FormCollection form) { string strDDLValue = form["ddlVendor"].ToString(); return View(MV); }</code>
Method 2: Use model
For the model binding method, add a property to your model:
<code class="language-csharp">public class MobileViewModel { public List<tbinsertmobile> MobileList; public SelectList Vendor { get; set; } public string SelectedVendor {get;set;} }</code>
In your view, bind the dropdown list to the model using @Html.DropDownListFor and specify the SelectedVendor property:
<code class="language-csharp">@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")</code>
Finally, in your controller, the selected value can be accessed via the SelectedVendor property:
<code class="language-csharp">[HttpPost] public ActionResult ShowAllMobileDetails(MobileViewModel MV) { string SelectedValue = MV.SelectedVendor; return View(MV); }</code>
Update: Post selected text
To capture both the selected value and its corresponding text, add a hidden field to your view:
<code class="language-csharp">public class MobileViewModel { public List<tbinsertmobile> MobileList; public SelectList Vendor { get; set; } public string SelectVendor {get;set;} public string SelectedvendorText { get; set; } }</code>
In your view, use JavaScript to update the selected item text in the hidden field:
<code class="language-javascript">$(function(){ $("#SelectedVendor").on("change", function() { $("#SelectedvendorText").val($(this).text()); }); }); @Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer") @Html.HiddenFor(m=>m.SelectedvendorText)</code>
The above is the detailed content of How to Get the Selected Value from a DropDownList in an MVC Controller?. For more information, please follow other related articles on the PHP Chinese website!