Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a dropdownlist that is populated from a database as:

Controller
C#
PayrollDb pdb = new PayrollDb ();
var addBranchGui = new branch();
addBranchGui.BranchTypes = new SelectList(pdb.branchtypes,"Id", "Type");

View
HTML
<p>Branch Type:@Html.DropDownListFor(x => x.BranchType, Model.BranchTypes, "Choose an option")</p>

This codes correctly populates the dropdownload list. Problem arises when user selects an option in the dropdownlist and submits the form and I catch the input data on [HttpPost action method and insert it into a database table, it is the "Id" field that gets inserted when I want the "Type" field to be inserted.

I can understand that on Postback event, browsers is reading "Id" field. Can someone please guide me how I can command the browser to give me the "Type" field so I can insert that into database.
Posted
Comments
Suvendu Shekhar Giri 8-Dec-15 14:49pm    
share the relevant code where you are fetching data from the form for insertion.
[no name] 8-Dec-15 15:18pm    
Answer is:

addBranchGui.BranchTypes = new SelectList(pdb.branchtypes,"Type", "Type");

1 solution

In the SelectList constructor, you are specifying Id as the data value field for the dropdown.
C#
addBranchGui.BranchTypes = new SelectList(pdb.branchtypes,"Id", "Type");

So it will render the dropdown like this
HTML
<select name="BranchType">
   <option value="2">HeadOffice
   <option value="4">Branch
</option></option></select>

So change it to use Type as the datavalue field.
C#
addBranchGui.BranchTypes = new SelectList(pdb.branchtypes,"Type", "Type");
This will render a SELECT element with same value for the option value and the option text
HTML
<select name="BranchType">
   <option value="HeadOffice">HeadOffice
   <option value="Branch">Branch
</option></option></select>

Now when user posts the form, you will get the text value(the type) in BranchType field.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900