我正在尝试创建一个局部视图以在每个视图上创建下拉列表。已创建一个视图模型和部分视图。它创建正确下拉但没有显示选定的值。
以下是View Model Class
public class drowDownVM
{
public string id { get; set; }
public string name { get; set; }
public string cssClass { get; set; }
public string keyColumnName { get; set; }
public string valueColumnName { get; set; }
public string selectedValue { get; set; }
public string viewbagName { get; set; }
public bool isMultipleSelect { get; set; }
public List<int> multipleselectedValue { get; set; }
}
以下是绑定下拉的部分视图
@if (Model != null)
{
if (ViewData != null && ViewData.Count > 0 && ViewData.Keys.Contains(Model.viewbagName))
{
string ddName = !(string.IsNullOrEmpty(Model.name)) ? Model.name : "default-name";
string viewBagName = !(string.IsNullOrEmpty(Model.viewbagName)) ? Model.viewbagName : ViewData.Keys.First();
string keyColumnName = !(string.IsNullOrEmpty(Model.keyColumnName)) ? Model.keyColumnName : "id";
string valueColumnName = !(string.IsNullOrEmpty(Model.valueColumnName)) ? Model.valueColumnName : "id";
string selectedVal = !(string.IsNullOrEmpty(Model.selectedValue)) ? Model.selectedValue : "";
List<int> multipleSelectVal = (Model.multipleselectedValue != null && Model.multipleselectedValue.Count > 0) ? Model.multipleselectedValue : new List<int>();
var cssClass = !(string.IsNullOrEmpty(Model.cssClass)) ? Model.cssClass : "";
if (!Model.isMultipleSelect)
{
<div>
@Html.DropDownList(ddName, new SelectList((System.Collections.IEnumerable)ViewData[viewBagName], keyColumnName, valueColumnName, 2), "--Select--", new { @class = cssClass, @data_Val = selectedVal })
</div>
}
else
{
@Html.ListBox(ddName, new MultiSelectList((System.Collections.IEnumerable)ViewData[viewBagName], keyColumnName, valueColumnName, multipleSelectVal), new { @class = cssClass, @multiple = "multiple"})
}
}
}
else
{
<p class="hidden">Model Data Not Found!</p>
}
下面是调用部分视图绑定下拉列表的代码,第一个是单选,第二个是调用多个选择。
@Html.Partial("_dropdown", new drowDownVM() { cssClass = "form-control", id = "TargetTypeList", keyColumnName = "code_val", name = "TargetTypeList", selectedValue = "1", valueColumnName = "code_name", viewbagName = "TargetTypeList"})
@Html.Partial("_dropdown", new drowDownVM() { cssClass = "form-control", id = "TargetTypeList", isMultipleSelect = true, keyColumnName = "code_val", name = "TargetTypeList", selectedValue = "1", valueColumnName = "code_name", viewbagName = "TargetTypeList", multipleselectedValue = new List<int>() { 1, 2 } })
答案 0 :(得分:0)
<div>
@Html.DropDownList(ddName, new SelectList((System.Collections.IEnumerable)ViewData[@ViewBag.ViewBagName], keyColumnName, valueColumnName, 2), "--Select--", new { @class = cssClass, @data_Val = selectedVal })
</div>