开发者

get selectlist text

开发者 https://www.devze.com 2023-02-27 06:15 出处:网络
when i bind my sel开发者_Go百科ect list to a dropdownlist in a view i see where i can get the selected value (but in my case, it\'s a number). is there a way i can get the description/text from the se

when i bind my sel开发者_Go百科ect list to a dropdownlist in a view i see where i can get the selected value (but in my case, it's a number). is there a way i can get the description/text from the select list?


Here is one way:

$(function() {
    $('select').change(function() {
        alert($('select option:selected').text());    
    });   

});

<select>
    <option value="0">Zero</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

Working jsfiddle: http://jsfiddle.net/wherC/

If you have multiple select elements on a page you will need to change the selector accordingly.


The the value of the selected option is what will be transferred as the form key of a select list.

Example

<select name="list1">
    <option selected value="1">one</option>
</select>

will produce a key list1=1

If you need the description, bind the description to the value of the select list.

<select name="list1">
    <option selected value="one">one</option>
</select>

will produce a key list1=one

If you are using SelectListItem this option would be:

new SelectListItem {
    Text = "one", 
    Value = "one" 
}


Not sure if I understand your question but :

Assuming our collection we want to use for populating our dropdown list is made from :

public class Animal
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Then you can populating your list would be

 @Html.DropDownListFor(model => model.AnimalId, new SelectList(AnimalList, "ID", "Name"))

For the sample above ID is the "Value" and Name would be displayed as option to choose. If you want it the other way around - just replace names of the class properties/fields

If you want both ID and Name to be displayed on the dropdown list to produce

<option value="1">1 - Horse</option>

I would go with

@Html.EditorFor(model => model.id, "PickAnimalTemplate", new { animals = ViewBag.Animals})

which is defining custom EditorTemplate for this property, where you can pretty much do whatever you want with the layout for example :

@foreach (var item in animals)
{
    <option value="@item.ID">@item.ID - @item.Name</option>
}
0

精彩评论

暂无评论...
验证码 换一张
取 消