【问题标题】:DropDownList does not have value when item is selected to pass on form submit下拉列表选择项目以传递表单提交时没有价值
【发布时间】:2020-03-19 22:01:14
【问题描述】:

这是 .NET MVC 项目的一部分。

我有一个 DropDownList,它由我的模型中的字符串数组填充。 The actual list functions fine and populates correctly, but when an item is selected, there is no value passed.该值应与从下拉列表中选择的文本相同。

我可以看到它可能没有分配到任何地方,但我对 MVC/HTML 项目相对缺乏经验。

        <div class="form-group">
            @Html.LabelFor(model => model.Cores, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Cores", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Cores, "", new { @class = "text-danger" })
            </div>
        </div>

我正在使用的代码是从我(显然)接管的一个更大的项目中修改而来的,所以我正在学习这个。

编辑:

这就是核心列表被初始化并传递到视图页面的方式。

var cores = db.Cores.ToList();
            var coreName = new List<string>();

            foreach (Core core in cores)
            {
                coreName.Add(core.Name);
            }

            ViewBag.Cores = new SelectList(coreName);

            return View();

【问题讨论】:

  • 这可能与“获取 DropDownList.Asp.NET MVC 的选定值”stackoverflow.com/questions/15881575/… 重复
  • 控制器动作签名是什么?在浏览器的调试工具中,生成的&lt;select&gt;name 是什么?在那些相同的工具中,值是否在 HTTP 请求中传递?这完全是表格的一部分吗?我们需要检查一个更大的图景。

标签: html asp.net-mvc


【解决方案1】:

您只是在创建一个未绑定到您的模型的下拉菜单。你应该使用Html.DropDownListFor,而不是Html.DropDownList

public class MyModel {
   public string Core { get; set; }
}

在您的视图文件中,

@Html.DropDownListFor(n => n.Core, (SelectList)ViewBag.Cores, htmlAttributes: new { @class = "form-control" })

并在控制器中发布操作

[HttpPost]
public ActionResult Report(MyModel model)
{
   //model.Core is selected core.
}

更新:

如果您没有模型,

在您的视图文件中,

@Html.DropDownList("Core", (SelectList)ViewBag.Cores, htmlAttributes: new { @class = "form-control" })

并在控制器中发布操作

[HttpPost]
public ActionResult Report(string Core)
{
   //Core is the selected one.
}

【讨论】:

  • 感谢您的回复。我应该在我原来的问题中包含这个,但是我的“Cores”变量是通过调用数据库来初始化的。我已经编辑了我的问题,以包括如何在 Controller 中准备模型。
  • @Lennac,如何填充核心并不重要,您也可以使用 ViewBag。这是关于如何从下拉列表中获取所选项目。我更新了我的答案。
  • 我收到一条错误消息,提示 HtmlHelper 不包含 DropDownListFor 的定义(这发生在开始添加 ViewBag.Cores 而不是“new SelectList(model.Cores)”时。如果我保留“ new SelectList(ViewBag.Cores)”列表加载,但仅作为对象类型“Mvc.SelectListItem”而不是实际文本值。同样,如果我使用你的最后一个示例,它表示 HtmlHelper 没有适用的方法命名为“DropDownList”
  • 是的,你是对的。ViewBag.Cores 必须转换为 SelectList,更新我的答案。
  • 做到了!非常感谢你的帮助。我认为(对我来说)困惑是在我的视图页面上我没有模型,而是使用了已初始化的 ViewBag。 post 操作获取值并创建模型(然后写入数据库)。再次,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
相关资源
最近更新 更多