Reputation: 1310
I want to get the name value not ID value from SelectList in mvc.
Here is my code
Controller
var occupationList = new SelectList(new[]
{
new { ID = 1, Name = "Student" },
new { ID = 2, Name = "House Wife" },
new { ID = 3, Name = "Business Man" },
new { ID = 4, Name = "Service Man" },
},
"ID", "Name", 1);
ViewData["occupationList"] = occupationList;
return View();
View
@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList, new {@class="control-label", style="width:250px;" })
Now, when I select the item from dropdownlist at that time it shows the selected item but it store the ID value in the database.
For ex : I select the Student
Name value from the dropdownlist and save it. Now, in database it store the 1
value.
But I dont want to store the ID value i.e. 1
. I want to store the Name value i.e. Student
in database.
Thank You.
Upvotes: 1
Views: 4497
Reputation: 1774
Use this code to save name in DB
@Html.DropDownList("Occupation", new SelectList(ViewData["occupationList"] as SelectList, "Name", "Name") , new { @class = "control-label", style = "width:250px;" })
Upvotes: 1
Reputation: 218762
When you submit the form, the selected option's value attribute is send from the browser to the server for that select element. If you want to send the name instead of the numeric id, you should set the data value field of the SelectList to be the name instead of Id
var occupationList = new SelectList(new[]
{
new { ID = 1, Name = "Student" },
new { ID = 2, Name = "House Wife" },
new { ID = 3, Name = "Business Man" },
new { ID = 4, Name = "Service Man" },
},
"Name", "Name", "Student");
ViewData["occupationList"] = occupationList;
Your view code will be same
@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList,
new {@class="control-label", style="width:250px;" })
This will render the markup for SELECT element with value and text set to the same field.
<select id="Occupation" name="Occupation">
<option value="Student" selected="selected">Student</option>
<option value="House Wife">House Wife</option>
<option value="Business Man">Business Man</option>
<option value="Service Man">Service Man</option>
</select>
As i mentioned earlier, now when you submit the form ,the string value will be submitted instead of the numeric Id. That means you need to make adjustments to your server side code to receive the string value and save it ( probably need to update the db schema as well to store the string value instead of numeric value)
Upvotes: 4