简体   繁体   中英

How can I return multiple values with a select list in ASP.NET MVC?

For example if I had a dropdownlist

 @Html.DropDownListFor(model => model.proj.price, Model.FoodSelectList, "Choose...")

The list displays a bunch of foods and each food has a price value that is returned when a food is selected. I would also like to store the name of the food item selected. How could I get both values back from the select list?

Thanks for the help I used something similar to this javascript

<script>
function myFunction()
{   var alertinfo = document.getElementById("Project_Price");
    var Project_Names = alertinfo.options[alertinfo.selectedIndex].text;
    $('#Project_Name).val(Project_Names);
}
</script>

Create a hidden field for the name:

@Html.HiddenFor(m => m.FoodName)

where FoodName is a property on the view model to store the name of the food. Then in JavaScript, leveraging jQuery here, set that value:

$('#{name_of_elem}').change(function() {
    // set yourVal somehow here
    var yourVal;

    $('#FoodName').val(yourVal);
});

where {name_of_elem} is the name of the drop down element. I think it's going to be proj_price , but I can't be sure, just look at the generated HTML.

It sounds like what you really need is a Food model which contains these values. Over-simplifying it might look like this:

public class Food
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Then in your view model you'd select the ID of the corresponding Food items, rather than the price or the name. So the select wouldn't contain the actual data, just a reference to the data. Its value would be the ID and its text would be the name (or price, or a combination thereof, whatever you want to display). Something like this perhaps:

@Html.DropDownListFor(model => model.proj.FoodID, Model.FoodSelectList, "Choose...")

In server-side code, given the ID of the entity selected, you'd fetch the entity itself from whatever the underlying data store is and then you'd have all of the information about that entity. For convenience it could even be lazy-loaded from the view model. Something like:

public int FoodID { get; set; }

public Food Food
{
    get
    {
        return Food.Fetch(FoodID);
    }
}

There are plenty of ways to accomplish that, some may fit your model structure more than others, so this is just an example to illustrate the idea. But the main point is that the select would be referencing the entity instead of trying to contain the entity, since a select (and HTTP POST values in general) is really just a key/value pair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM