ASP.NET - back panel alias dropdown names
I am using .NET 3.5, MVC.
I want to use a set of string aliases to represent database values. that is, when the user selects an option from the dropdown, it actually sets the value in the table to 0, 1, 2, etc., not the text shown in the dropdown.
eg. I am doing:
IdName[] Thing = new[] {
new IdName { Id = 0, Name = "No Selection" },
new IdName { Id = 1, Name = "Thing A9" },
new IdName { Id = 2, Name = "Thing C12" },
new IdName { Id = 3, Name = "Thing F4" }
};
MyDropDownList = new SelectList(Things, "Id", "Name",0);
and in the view:
<%= Html.DropDownList("MyDropDownList")%>
This works fine now. What I can't seem to get it to work is displaying the field value in the "detail" view and showing "Thing C12" as text instead of "2".
Also, is this the best way to do it? I don't want to use the actual string in the database if I change the text in the record (for example, change the name "Thing F4" to "Thing F5".) I'm completely open to some other ideas.
Thank!
source to share
So, you want your action method (which retains the user's selection) to store the value, not the alias shown in the dropdown.
I think you have two options.
1- On the server side, getting a value (id) from your datasource, eg: the Things [] array in your example.
public ActionResult StoreValueFromDropDown(string MyDropDownList) {
var id = Things.Single(thing => thing.Name == MyDropDownList).Id;
// here goes the code to sotre the id
}
2- client side by adding a hidden field that stores the dropdown value. here is an example using jQuery (I haven't tested it):
<input type="hidden" id="ThingId" />
$('#MyDropDownList').change(function(e){
$('#ThingId').value($('#MyDropDownList option:selected').attr('value'));
});
then you need to change your action method to accept the value of this hidden field
public ActionResult StoreValueFromDropDown(int ThingId) {
// here goes the code to sotre the id
}