Thursday, May 5, 2011

ASP.NET - Alias dropdownlist names on back end

I'm using .NET 3.5, MVC.

I want to use a set of string aliases to represent database values. i.e. when a user selects an option from a dropdown it actually sets the value as 0, 1, 2, etc. in the table, rather than the text shown in the dropdown itself.

e.g. I'm 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")%>

Now, this works just fine. What I can't get to work is displaying the value of the field in a 'details' view and showing "Thing C12" as the text instead of "2".

Also, is this the best way to go about this? I don't want to use the actual string in the database in case I modify the text on an entry (e.g. change the name of "Thing F4" to "Thing F5".) I'm totally open to some other ideas.

Thanks!

From stackoverflow
  • So you want your action method (that will store the user choice) to store the value rather than the alias shown on the Dropdown.

    I think you have two options here.

    1- On the server side by getting the value(the id) from your data source, 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- on the client side by adding a hidden field that store the value of the Dropdown. here is an example using jQuery(I didn't test it):

    <input type="hidden" id="ThingId" />
    

    ,

    $('#MyDropDownList').change(function(e){
         $('#ThingId').value($('#MyDropDownList option:selected').attr('value'));
    });
    

    then you need to modify your action method to accept the value of that hidden field

    public ActionResult StoreValueFromDropDown(int ThingId) {
    
            // here goes the code to sotre the id
    }
    
    : I'm storing the value in the database without issue - it was retrieving the value and translating it back to text that was the issue. I did manage to solve my problem by creating a custom view controller and adding a method to perform a lookup on the 'Thing' list using the value found in the database record. Now my issue is that I'm going to have to create a lot of field-specific methods like this (along with a bunch of 'Thing' lists) and I imagine there is a better way to do it to ensure that things are less model-specific. Nonetheless, thanks for your help.
    : I think this issue may be more general. I tried to simplify and got no better results. I've started another question to try to figure that out.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.