Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

What I have tried:

I tried many thing but nothing worked.
Posted
Updated 15-Nov-17 3:40am

Quote:
But I dont want to store the ID value i.e. 1. I want to store the Name value i.e. Student in database.

if you dont want the ID value then assign the Text to ID

var occupationList = new SelectList(new[] 
{
    new { ID =  "Student", Name = "Student" },
    new { ID = "House Wife", Name = "House Wife" },
    new { ID = "Business Man", Name = "Business Man" },
    new { ID = "Service Man", Name = "Service Man" },
},
 
Share this answer
 
v3
The name isn't sent with the post so you can't read it using traditional methods. If your data is hard-coded then you already know what the ID equates to.

private List<MyData> GetData()
{
    return new List<MyData> {
        new MyData{ ID=1, Name="Student" },
        new MyData{ ID=2, Name="House Wife" },
        new MyData{ ID=3, Name="Business Man" },
        new MyData{ ID=4, Name="Service Man" },
    };
}

[HttpGet]
public ActionResult Index()
{
    var occupationList = new SelectList(GetData(),
    "ID", "Name", 1);

    ....

    // when the form is posted get the ID then get the name from the data
    int postedID = 1;
    string name = GetData().FirstOrDefault(d => d.ID == postedID).Name;

    ....


Edit: By the day, you *do* want to store the ID and not the text, trust us on that as it'll come back and bite you if you don't maintain data integrity in this way.
 
Share this answer
 
v2

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