I am working on MVC 4.0.
I need to access my dropdown box Text (not value) using Request.Form("ddlId") in my controller code.
and display the selected info on confirmation page of registration.
i.e. lets consider I am having Country dropbox as below.
<select data-val="true" data-val-required="Required" id="CountryId" name="CountryId" style="width:210px"><option value="">--Select--</option><option value="1">USA</option><option value="2">UK</option></select>
now, in controller when i use,
objWizard.CountryId = Request.Form["CountryId"];
I got the value of COuntry dropbox, not the text selected by user.
How can i select text of dropbox using Request.Form(...)????
Or any alternative........
My jquery code is as below.
$.post( '@Url.Action("ConfirmDetails", "Wizard")', $("form").serialize(), function (r)
{
// inject response in confirmation step
//$(".wizard-step:visible")
$("#confirmdiv").html(r);
});
i'll assume that you are posting a form and that look likes
<form>
<select id="CountryId">
<option value=1>US</option>
<option value=2>UK</option>
</select>
<input type="submit" value="submit" id="btnSubmit"/>
</form>
on form submit cancel the default behavior
$("#btnSubmit").click(function(e){
e.preventDefault();
//now make a hidden field here and put the text of selected option in that
var selectedOption = $("#CountryId option:selected").text();
$("<input/>",{type:'hidden',name:'CountryName'}).val(selectedOption).appendTo("form");
// now post the form
$.post( '@Url.Action("ConfirmDetails", "Wizard")', $("form").serialize(),function (r)
{
// inject response in confirmation step
//$(".wizard-step:visible")
$("#confirmdiv").html(r);
});
});
in the controller
[HttpPost]
public ActionResult ConfirmDetails()
{
var countryName = Request.Form["CountryName"];
}
You can use JQuery post for this,
var selectedLi=$('#CountryId option:selected');
$.post('controller/action',{CountryId :selectedLi.val(),CountryName:selectedLi.text() }, function(data) {
$('.result').html(data);
});
And in your action you can get those values like this,
public ActionResult Action(string CountryName,string CountryId )
{
//...........
}
You could emit the value tag as the country name on the server and prevent any need for javascript.
<select id="CountryId">
<option value="US">US</option>
<option value="UK">UK</option>
</select>
You can use,
ddlHospitalName.Items.FindByValue(Convert.ToString(Request.Form["ctl00$contentPlaceHolder$ddlHospitalName"])).Text;