问题描述
我正在尝试在Model的下拉列表中显示类似于Model.list<AnotherModel>.List<string>
的名称。
模型
public class LoginModel
{
public List<ApplicationNames> ApplicationName { get; set; }
}
public class ApplicationNames
{
public string Id { get; set; }
public List<string> Applications { get; set; }//["app1","app2"]
}
CSHTML
@model LoginModel
@using (Html.BeginForm("ApplicationIndex","Home",FormMethod.Get))
{
@Html.DropDownListFor(m => m.ApplicationName,new SelectList(Model.ApplicationName,"Id","Applications"),"Select Application",new { @class = "textBoxStyle",placeholder = "Select your application...",autofocus = "autofocus",autocomplete = "on",onkeypress = "btnFocusActivate(this,event)",id = "un" })
<input type="submit" value="NEXT" class="rectangle" id="submitNext" disabled="disabled" />
}
在下拉列表中而不是应用程序中,我正在获取GenericList.Object
。
要在下拉列表中获得Applications
的名称,我需要进行哪些修改?
结果类似:
谢谢。
解决方法
您的课必须简单明了。
public class LoginModel
{
public string SelectedApplicationNameItemId { get; set; }
public List<ApplicationNameItem> ApplicationNames { get; set; }
}
public class ApplicationNameItem
{
public string Id { get; set; }
public string Name { get; set; }
}
Razor页面的代码如下。提交后,所选值可以位于SelectedApplicationNameItemId
属性中
Html.DropDownListFor(m => m.SelectedApplicationNameItemId,new SelectList(Model.ApplicationNames,"Id","Name"))
,
在下拉列表中而不是应用程序中,我正在获取GenericList.Object。
要在下拉列表中获得应用程序名称,我需要修改什么?
public List<string> Applications { get; set; }//["app1","app2"]
您可以尝试使用指定的分隔符来连接字符串项目,如下所示。
@Html.DropDownListFor(m => m.ApplicationName,new SelectList(Model.ApplicationName.Select(a=>new { Id = a.Id,Applications = String.Join(",",a.Applications.ToArray())}),"Applications"),"Select Application",new { @class = "textboxStyle",placeholder = "Select your application...",autofocus = "autofocus",autocomplete = "on",onkeypress = "btnFocusActivate(this,event)",id = "un" })
测试结果
更新:
可以在运行时编辑/附加带有id的随机数,并像每个应用一样将结果作为单独的选项。
要达到上述要求,正如我在评论中提到的那样,您可以尝试根据控制器操作中的模型数据生成预期数据,然后将其传递给视图以填充下拉列表,如下所示。
var Applications_list = "";
foreach (var item in model.ApplicationName)
{
Applications_list += String.Join(",item.Applications.ToArray()) + ",";
}
ViewBag.AppList = Applications_list.TrimEnd(',').Split(",").Select((a,index) => new { Id = index,AppName = a });
HTML代码
@Html.DropDownListFor(m => m.ApplicationName,new SelectList(ViewBag.AppList,"AppName"),id = "un" })
测试结果