添加属性以选择列表选项 [英] Add attribute to select list option
问题描述
我在 Razor 视图的下拉列表中有一个项目列表.在数据库中,每个项目都有 3 个与之关联的值 - 数据库 ID、短名称(用于显示)和长名称(用于传递给服务).下拉列表必须显示短名称,因此我使用数据库 ID 作为值和短名称作为文本填充下拉列表.
但是,当用户选择一个项目时,我需要将长名作为查询参数用作使用jQuery的搜索服务,例如,当Cortina是福特Cortina 1979蓝色"时,需要传递给服务.我的第一个想法是将长名称存储为数据破折号属性,但我想知道是否有更好的方法.所以- 如何在下拉列表中存储所有 3 个值?
- 如果我确实使用数据破折号属性,我该如何将所有 LONG_NAME 值合并到 Html.DropDownListFor 或以某种方式将它们添加到下拉列表中?
数据库:
CARID SHORT_NAME LONG_NAME1 毒蛇道奇毒蛇 19822 Boxster 保时捷 Boxster 2009 黑色3 Cortina 福特 Cortina 1979 蓝色
用于创建下拉菜单的控制器助手:
public static IEnumerableGetSelectList(这个 IEFRepository 存储库,字符串类型名称){var Vehicle = repository.TypeTypes.FirstOrDefault(t => t.Name.ToUpper() == typeName);如果(车辆!= null){var carList = Vehicle.SubTypes.ToList().OrderBy(s => s.Name);var selectList = new SelectList(subTypeList, "SubTypeID", "Name");返回选择列表;}}
这是我用来创建下拉菜单的代码:
@Html.DropDownListFor(model => model.CarID,new SelectList(ViewBag.Cars, "Value", "Text", "1"))@Html.ValidationMessageFor(model => model.CarShortName)
输出如下:
"<select id="CarID" name="CarID" data-val="true" data-val-number="CarID 字段必须是数字."data-val-required="CarID 字段是必需的."><option value="2">Boxster</option><option value="3">Cortina</option><option selected="selected" value="1">Viper</option></选择>
现在才回到这个问题.虽然@nikeaa 的回答肯定是一个可行的解决方案,但我认为它有点重量级,尤其是使用 XDocument.提醒一下,我正在处理的是 TypeType(汽车)和 SubType(汽车类型列表 - Viper、Granada、Hunter、Zodiac、Wolsley 1660 等).TypeType 也可以是卡车、自行车等.所以这是我解决它的方法:
我在控制器上添加了一个 JsonResult 方法来返回一个具有我想要的 3 个属性的匿名对象:
public class VehicleController : 控制器{//等等.公共 JsonResult GetSubTypesForTypeType(string typeTypeName){var car = pronova2Repository.GetTypeWithSubTypes(typeTypeName);返回汽车 == 空?Json(新对象[0],JsonRequestBehavior.AllowGet): Json(cars.SubTypes.OrderBy(s => s.Name).Select(=>新 { s.SubTypeID, s.Name, s.Description }).ToArray(),JsonRequestBehavior.AllowGet);}//等等.}
然后在js中:
填充下拉列表:
//填充SELECT列表时的汽车下降if ($('select#SubTypeID').length) {var carsSelect = $('select#SubTypeID');var carsList = populateCarsList("CARS");var carsListHtml = createCarsSelectList(carsList);汽车选择.html('');汽车选择.append(carsListHtml);$('#SubTypeID').change(function (e) {clearFormData();});}
通过ajax调用调用一个函数来获取子类型(汽车):
function populateCarsList(typeTypeName) {var 汽车列表;$.ajax({url: '/Vehicle/GetSubTypesForTypeType',数据:{ typeTypeName: typeTypeName },异步:假}).完成(功能(数据){汽车列表 = 数据;}).错误(功能(味精,网址,行){alert("从 Vehicle/GetSubTypesForTypeType 检索汽车时出错.错误信息:" + line);});返回汽车列表;}
使用添加的描述作为data-*"属性创建选择列表的功能:
function createCarsSelectList(selectData) {var html = '',len = selectData.length,选择,描述;for (var i = 0; i < len; i++) {//默认情况下应该选择Viper"if (selectData[i].Name.toLocaleUpperCase() === "VIPER") {选择 = ' 选择 = = 选择" ';} 别的 {选择 = '';}//添加描述(作为data-"属性),一些描述为空if (selectData[i].Description != null) {description = selectData[i].Description;} 别的 {描述 = '';}html += '<option value="' + selectData[i].SubTypeID + '" data-description="' + description + '"' + selected + '>'+ selectData[i].Name + '';}返回html;}
I have a list of items in a drop down list within a Razor view. In the database each item has 3 values associated with it - the database id, short name (for display), and long name (for passing to a service). The drop down must show the short name, so I'm populating the drop down with the database id as the value and the short name as the text.
However when a user selects an item I need pass the long name as a query parameter to a search service using jQuery, e.g when Cortina is seleted "Ford Cortina 1979 Blue" needs to be passed to the service. My first thought is store the long name as a data dash attribute but I'm wondering is there a better way. So
- How do I store all 3 values in the drop down list?
- If I do use data dash attributes how do I incorporate all the LONG_NAME values into Html.DropDownListFor or somehow add them to the drop down list?
DB:
CARID SHORT_NAME LONG_NAME
1 Viper Dodge Viper 1982
2 Boxster Porsche Boxster 2009 Black
3 Cortina Ford Cortina 1979 Blue
Controller helper to create the drop down:
public static IEnumerable<SelectListItem> GetSelectList(this IEFRepository repository, string typeName)
{
var vehicle = repository.TypeTypes.FirstOrDefault(t => t.Name.ToUpper() == typeName);
if (vehicle != null)
{
var carList = vehicle.SubTypes.ToList().OrderBy(s => s.Name);
var selectList = new SelectList(subTypeList, "SubTypeID", "Name");
return selectList;
}
}
Here's the code I use to create the drop down:
<div class="editor-field">
@Html.DropDownListFor(model => model.CarID,
new SelectList(ViewBag.Cars, "Value", "Text", "1"))
@Html.ValidationMessageFor(model => model.CarShortName)
</div>
Here's the output:
<select id="CarID" name="CarID" data-val="true" data-val-number="The field CarID must be a number." data-val-required="The CarID field is required.">
<option value="2">Boxster</option>
<option value="3">Cortina</option>
<option selected="selected" value="1">Viper</option>
</select>
Just getting back to this now. While @nikeaa's answer is certainly a viable solution I thought it was a bit heavyweight especially using XDocument. As a reminder what I'm dealing with is a TypeType (Cars) and SubType (list of car types - Viper, Granada, Hunter, Zodiac, Wolsley 1660, etc). TypeType could also be Trucks, Bicycles, etc. So here's how I solved it:
I added a JsonResult method on the Controller to return an anonymous object with the 3 properties that I wanted:
public class VehicleController : Controller
{
// etc.
public JsonResult GetSubTypesForTypeType(string typeTypeName)
{
var cars = pronova2Repository.GetTypeWithSubTypes(typeTypeName);
return cars == null
? Json(new object[0], JsonRequestBehavior.AllowGet)
: Json(cars.SubTypes.OrderBy(s => s.Name).Select(
s => new { s.SubTypeID, s.Name, s.Description }).ToArray(),
JsonRequestBehavior.AllowGet);
}
// etc.
}
Then in js:
Populate the drop down:
// populate the cars drop down when the select list is available
if ($('select#SubTypeID').length) {
var carsSelect = $('select#SubTypeID');
var carsList = populateCarsList("CARS");
var carsListHtml = createCarsSelectList(carsList);
carsSelect.html('');
carsSelect.append(carsListHtml);
$('#SubTypeID').change(function (e) {
clearFormData();
});
}
Call a function to get the subtypes (cars) via an ajax call:
function populateCarsList(typeTypeName) {
var carsList;
$.ajax({
url: '/Vehicle/GetSubTypesForTypeType',
data: { typeTypeName: typeTypeName },
async: false
}).done(function (data) {
carsList = data;
}).error(function (msg, url, line) {
alert("Error retrieving cars from Vehicle/GetSubTypesForTypeType. Error message: " + line);
});
return carsList;
}
Function to create the select list with the added description as a "data-*" attribute:
function createCarsSelectList(selectData) {
var html = '',
len = selectData.length,
selected,
description;
for (var i = 0; i < len; i++) {
// "Viper" should be selected by default
if (selectData[i].Name.toLocaleUpperCase() === "VIPER") {
selected = ' selected="selected" ';
} else {
selected = '';
}
// Add the description (as a "data-" attribute), some descritions are null
if (selectData[i].Description != null) {
description = selectData[i].Description;
} else {
description = '';
}
html += '<option value="' + selectData[i].SubTypeID + '" data-description="' + description + '"' + selected + '>' + selectData[i].Name + '</option>';
}
return html;
}
这篇关于添加属性以选择列表选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!