[英]Razor Html.DropDownListFor automatically set the selected value
[英]MVC5 Razor html.dropdownlistfor set selected when value is in array
我正在開發一個 ASP.NET MVC 5 應用程序,使用 C# 和 .NET Framework 4.6.1。
我有這個View
:
@model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
ViewModel
是:
public class AggregationLevelConfViewModel
{
private readonly List<GenericIdNameType> codeTypes;
private readonly List<GenericIdNameType> helperCodeTypes;
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
public AggregationLevelConfViewModel()
{
// Load CodeTypes to show it as a DropDownList
byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
codeTypes = new List<GenericIdNameType>();
helperCodeTypes = new List<GenericIdNameType>();
for (int i = 0; i < values.Length; i++)
{
GenericIdNameType cType = new GenericIdNameType()
{
Id = values[i].ToString(),
Name = EnumHelper.GetDescription((CodeTypes)values[i])
};
if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
codeTypes.Add(cType);
helperCodeTypes.Add(cType);
}
}
}
而Models.AggregationLevelConfiguration
是:
public class AggregationLevelConfiguration
{
public byte AggregationLevelConfigurationId { get; set; }
public int ProductionOrderId { get; set; }
public string Name { get; set; }
public byte CodeType { get; set; }
public byte HelperCodeType { get; set; }
public int PkgRatio { get; set; }
public int RemainingCodes { get; set; }
}
我需要在這些屬性中設置選定的值:
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
但是我不能在new SelectList(codeTypes, "Id", "Name");
設置它new SelectList(codeTypes, "Id", "Name");
或new SelectList(helperCodeTypes, "Id", "Name");
因為所選值位於Configurations
數組中:字段AggregationLevelConfiguration.CodeType
和AggregationLevelConfiguration.HelperCodeType
。
我想我必須在視圖中設置選定的值,但我不知道該怎么做。
如何設置選定的值?
不幸的是, @Html.DropDownListFor()
在循環渲染控件時的行為與其他助手略有不同。 這之前已在 CodePlex 上報告為問題(不確定是錯誤還是限制)
有 2 個選項可以解決此問題,以確保根據模型屬性選擇正確的選項
選項 1 (使用EditorTemplate
)
為集合中的類型創建自定義EditorTemplate
。 在/Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml
創建部分(注意名稱必須與類型名稱匹配
@model yourAssembly.AggregationLevelConfiguration
@Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
然后在主視圖中,將SelectList
作為additionalViewData
傳遞給EditorTemplate
@using (Html.BeginForm())
{
...
@Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
選項 2 (在每次迭代中生成一個新的SelectList
並設置selectedValue
)
在此選項中,您的屬性CodeTypeItems
應該是IEnumerable<GenericIdNameType>
,而不是SelectList
(或只是使codeTypes
成為公共屬性)。 然后在主視圖中
@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
旁注:無需使用new { id = "Configurations[0].HelperCodeType"
- DropDownListFor()
方法已經生成了該id
屬性
我編寫了這個類來解決我在 html 選擇列表中選擇一個選項時遇到的問題。 我希望它可以幫助某人。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Login_page.Models
{
public class HTMLSelect
{
public string id { get; set; }
public IEnumerable<string> @class { get; set; }
public string name { get; set; }
public Boolean required { get; set; }
public string size { get; set; }
public IEnumerable<SelectOption> SelectOptions { get; set; }
public HTMLSelect(IEnumerable<SelectOption> options)
{
}
public HTMLSelect(string id, string name)
{
this.id = id;
this.name = name;
}
public HTMLSelect(string id, string name, bool required, IEnumerable<SelectOption> options)
{
this.id = id;
this.name = name;
this.required = required;
}
private string BuildOpeningTag()
{
StringBuilder text = new StringBuilder();
text.Append("<select");
text.Append(this.id != null ? " id=" + '"' + this.id + '"' : "");
text.Append(this.name != null ? " name=" + '"' + this.name + '"' : "");
text.Append(">");
return text.ToString();
}
public string GenerateSelect(IEnumerable<SelectOption> options)
{
StringBuilder selectElement = new StringBuilder();
selectElement.Append(this.BuildOpeningTag());
foreach (SelectOption option in options)
{
StringBuilder text = new StringBuilder();
text.Append("\t");
text.Append("<option value=" + '"' + option.Value + '"');
text.Append(option.Selected != false ? " selected=" + '"' + "selected" + '"' + ">" : ">");
text.Append(option.Text);
text.Append("</option>");
selectElement.Append(text.ToString());
}
selectElement.Append("</select");
return selectElement.ToString();
}
}
public class SelectOption
{
public string Text { get; set; }
public Boolean Selected { get; set; }
public string Value { get; set; }
}
}
和
public IEnumerable<SelectOption> getOrderTypes()
{
List<SelectOption> orderTypes = new List<SelectOption>();
if (this.orderType == "OptionText")
{
orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
} else
{
orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
}
}
並使用它:
@{
Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
}
@Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
我離開這個以防它幫助別人。 我有一個非常相似的問題,但沒有一個答案有幫助。
我們在頂部看到了這一行:
IEnumerable<SelectListItem> exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable<string>).Select(e => new SelectListItem() {
Value = e,
Text = e,
Selected = Model.ExitFromTrustDeed == e
});
然后在視圖下方:
@Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { @class = "form-control" })
我們在我的 ViewData 中有一個與lambda 表達式的選擇器同名的屬性,並且由於某種原因使得下拉列表在沒有選擇任何選項的情況下呈現。
我們將 ViewData 中的名稱更改為ViewData["ExitFromTrustDeed2"]
並使其按預期工作。
雖然很奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.