【问题标题】:Dropdown list from table in ASP NET MVCASP NET MVC 中表的下拉列表
【发布时间】:2014-11-24 20:18:02
【问题描述】:

我想从表格中获取包含值的下拉列表。我有模特:

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; }
    }

}

在控制器中我为此模型创建动作:

    public ActionResult Create()
    {
        return View();
    }

在视图中:

@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.MasterList 是 null 。但为什么?在模型中,我告诉从另一个模型获取列表(public List MasterList { get; set; })。为什么是空的?

【问题讨论】:

  • 向我们展示你想加载模型的控制器代码..
  • C# MVC get values from dropdownlist 太简单了GOOGLE SEARCH 可以Yield
  • Model.MasterList 为 null 。但是为什么呢? - 是什么让你认为它不会是?
  • 试试this topic。有一个关于如何创建DropDownList的解释。
  • 但它总是告诉我 Model.MasterList 为空 目前,根据您的代码,您没有向 View 返回任何内容:return View() // it's EMPTY。因此,您的模型为空,即使视图需要 Mobile。稍后,查找SelectListDropDownList。 SelectList 可能很棘手,但一旦你理解了它,创建DropDonwList 甚至更好DropFownListFor 很容易

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

此代码是在 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"})

【讨论】:

    【解决方案2】:

    当您查询 Mobile 时,您需要包含(“MasterList”),或者在您的上下文中开启延迟加载(不推荐)

    【讨论】:

      【解决方案3】:

      我的答案是将其添加到控制器:

         public ActionResult Create()
          {    
           ViewBag.MasterId = new SelectList(db.Masters, "Id", "Name");
           return View();
          }
      

      然后在视图中显示下拉列表:

       @Html.DropDownList("MasterId", null, htmlAttributes: new { @class = "form-control" })
      

      Thnx ZikO 让我现在该列表没有自动加载。

      【讨论】:

        猜你喜欢
        • 2012-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-03
        • 2021-07-17
        • 1970-01-01
        相关资源
        最近更新 更多