C# ASP NET MVC中表格的下拉列表
我想从表中获取带有值的下拉列表。我有一个模特:C# ASP NET MVC中表格的下拉列表,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我想从表中获取带有值的下拉列表。我有一个模特: namespace MobileService.Models { public class Mobile { public int Id { get; set; } public string Model { get; set;} Public string EMEI { get; set ;} public int Mas
namespace MobileService.Models
{
public class Mobile
{
public int Id { get; set; }
public string Model { get; set;}
Public string EMEI { get; set ;}
public int MasterId { get; set; }
public List<Master> MasterList { get; set; }
}
public class Master
{
public int Id { get; set; }
public string Name { get; set; }
}
}
鉴于:
@model MobileService.Models.Mobile
@using (Html.BeginForm()) {
@Html.EditorFor(model => model.Model)
@Html.EditorFor(model => model.EMEI )
// And here i want to display a dropdown list with all available masters
<button type="submit" class="btn btn-primary">Creat</button>
}
@model MobileService.Models.Mobile
@使用(Html.BeginForm()){
@EditorFor(model=>model.model)
@EditorFor(model=>model.EMEI)
//在这里,我想显示一个下拉列表,其中包含所有可用的母版
创造
}
但它总是告诉我Model.MasterList为空。但是为什么呢?在模型中,我告诉从另一个模型获取列表(公共列表主列表{get;set;})。为什么为空?这段代码是用VB编写的。在开始的时候,即使我找了很多时间,这也是我找到的简单解决方案 将模型转换为selectListItems列表
Dim lstEmpTypes As New List(Of SelectListItem)
lstTicketWrTypes.Add(New SelectListItem With {.Text = row("Something"), .Value = row("Something")})
'然后将其加载到ViewBag中
ViewBag.EmpTypes = lstEmpTypes
在你看来
@Html.DropDownList("selectWrType", New SelectList(ViewBag.EmpTypes , "Value", "Text"), New With {.class = "span3"})
当您查询移动设备时,您需要包括(“主列表”),或在您的上下文中打开延迟加载(不推荐)我的答案是将此添加到控制器:
public ActionResult Create()
{
ViewBag.MasterId = new SelectList(db.Masters, "Id", "Name");
return View();
}
然后,为了显示液滴列表:
@Html.DropDownList("MasterId", null, htmlAttributes: new { @class = "form-control" })
ThnxZikO谁让我现在知道该列表不是自动加载的。向我们显示您假设加载模型的控制器代码。。令人惊讶的是,一个简单的
谷歌搜索
可以产生
模型。主列表为空。但是为什么呢你凭什么认为不会呢?试试看。关于如何创建DropDownList
有一个解释。但它总是告诉我Model.MasterList当前为空,根据您的代码,您没有返回任何要查看的内容:return View()//它是空的
。因此,您的模型为空,即使视图期望Mobile
。稍后,查找SelectList
和DropDownList
。SelectList可能很棘手,但一旦您理解了它,就可以很容易地创建DropDonwList
,甚至更好地创建DropFownListFor
@Html.DropDownList("MasterId", null, htmlAttributes: new { @class = "form-control" })