添加属性选择列表选项 [英] Add attribute to select list option
问题描述
我在下拉列表中选择一个剃刀视图中的项目的列表。数据库中的每个项目都有与它相关的3个值 - 数据库ID,短名称(显示),长文件名(用于传递到服务)。下拉必须显示短名称,所以我填充下拉与数据库ID作为价值和短名称的文本。
然而,当用户选择我需要经过漫长的名称使用jQuery的查询参数搜索服务时,科尔蒂纳入围福特Cortina的1979年蓝色需要传递给服务例如一个项目。我首先想到的是长名称存储为数据破折号属性,但我不知道有没有更好的办法。因此,
- 如何存储在下拉列表中的所有3个值?
- 如果我使用的数据属性几许我如何将所有的LONG_NAME值到Html.DropDownListFor或以某种方式将其添加到下拉列表?
DB:
CARID SHORT_NAME LONG_NAME
1蝰蛇道奇蝰蛇1982年
Boxster的2款保时捷Boxster黑色2009年
3科尔蒂纳丹福特Cortina的1979年蓝色
控制器助手向下创建降:
公共静态的IEnumerable< SelectListItem> GetSelectList(这IEFRepository库,字符串的typeName)
{
VAR车辆= repository.TypeTypes.FirstOrDefault(T => t.Name.ToUpper()== typeName的);
如果(车辆!= NULL)
{
。VAR卡洛斯= vehicle.SubTypes.ToList()排序依据(S = GT; s.Name);
VAR选择列表=新的SelectList(subTypeList,SubTypeID,姓名); 返回选择列表;
}
}
这里的code我用下来创建降:
< DIV CLASS =主编场>
@ Html.DropDownListFor(型号=> model.CarID,
新的SelectList(ViewBag.Cars,值,文本,1))
@ Html.ValidationMessageFor(型号=> model.CarShortName)
< / DIV>
下面是输出:
<选择一个id =CarIDNAME =CarID数据-VAL =真正的数据-VAL-数=carid字段必须是数字数据-VAL-所需=是必需的CarID领域。>
<期权价值=2>的Boxster< /选项>
<期权价值=3>&科尔蒂纳丹LT; /选项>
<选项选择=选择值=1>蝰蛇LT; /选项>
< /选择>
刚刚回到这个现在。而@ nikeaa的回答无疑是一个可行的解决方案我认为这是特别是在使用的XDocument有点重量级。正如我正在处理一个提醒是TypeType(汽车)和子类型(汽车类型的列表 - 蝰蛇,格拉纳达,猎人,十二生肖,Wolsley 1660等)。 TypeType也可能是卡车,自行车等。
因此,这里是我如何解决它:
我在控制器上增加了一个JsonResult方法与3个属性,我想返回一个匿名对象:
公共类VehicleController:控制器
{
//等等。
公共JsonResult GetSubTypesForTypeType(字符串typeTypeName)
{
VAR汽车= pronova2Repository.GetTypeWithSubTypes(typeTypeName); 返回汽车== NULL
? JSON(新对象[0],JsonRequestBehavior.AllowGet)
:JSON(cars.SubTypes.OrderBy(S = GT; s.Name)。选择(
S =>新{s.SubTypeID,s.Name,s.Description})。ToArray的()
JsonRequestBehavior.AllowGet);
}
//等等。
}
然后在JS:
填充下拉:
//填充汽车下拉时选择列表可用
如果($('#选择SubTypeID')。长){
VAR carsSelect = $('#选择SubTypeID');
VAR carsList = populateCarsList(CARS);
VAR carsListHtml = createCarsSelectList(carsList);
carsSelect.html('');
carsSelect.append(carsListHtml); $('#SubTypeID')。改变(函数(五){
clearFormData();
});
}
调用函数通过Ajax调用来获取亚型(汽车):
函数populateCarsList(typeTypeName){
VAR carsList; $阿贾克斯({
网址:'/车/ GetSubTypesForTypeType',
数据:{typeTypeName:typeTypeName},
异步:假的
})。完成(功能(数据){
carsList =数据;
})错误(功能(味精,网址,线){
警报(错误从车辆/ GetSubTypesForTypeType错误信息检索汽车:+线);
}); 返回carsList;
}
函数来创建与添加的说明选择列表作为数据 - *属性:
函数createCarsSelectList(selectData){
变种的html ='',
LEN = selectData.length,
选择
描述; 对于(VAR I = 0; I< LEN,我++){ //毒蛇应该是默认选择
如果(selectData [I] .Name.toLocaleUpperCase()===毒蛇){
选择='选择=选择;
}其他{
选择='';
} //添加描述(作为一个数据 - 属性),有些descritions为null
如果(selectData [I]。说明!= NULL){
说明= selectData [I]。说明;
}其他{
说明='';
} HTML + ='<期权价值=+ selectData [I] .SubTypeID +'数据说明=+说明+''+选+'>' + 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屋!