【问题标题】:DropdownListFor value not settingDropdownListFor 值未设置
【发布时间】:2020-04-01 18:59:46
【问题描述】:

我正在处理 Razor View 中的一个问题。 DropDown 工作正常,但所选值设置不正确。该值是从控制器设置的,但在视图中 @Html.DropDownListFor 值未设置。任何帮助都将受到高度赞赏。提前致谢!这是我的代码。

查看:

@Html.LabelFor(x => x.BranchID, htmlAttributes: new { @class = "col-2 col-form-label" })
<div class="col-md-3">
    @Html.DropDownListFor(x => x.BranchID, new SelectList(Model.listofBranch, "BranchID", "BranchName"), new { @class = "form-control m-input", @id = "BranchID" })
    @Html.ValidationMessageFor(model => model.BranchID, "", new { @class = "text-danger" })
</div>

控制器

mdlGRN.BranchID = obj.BranchID;
return View(mdlGRN);

【问题讨论】:

  • 我认为如果您编辑您的问题以显示您如何设置 listofBranch 将会很有帮助。您是否还检查了分配给 BranchID 的值,如果是,它是什么?
  • 我正在从 Db 设置 listofBranch 的值,这工作正常。此外 BranchID 是 Int 并且也是正确的,它只是没有在任何编辑器上设置,除了 @Html.Display
  • 我并不是说它不能正常工作。但我仍然认为查看您在下拉列表中输入的内容会有所帮助。例如,如果它是一个字符串数组,可以解释为什么你的值没有被填充。
  • 我添加了描述 BranchID 值的屏幕截图。我正在使用列表从数据库中获取所有这些数据。
  • 我已经用一些测试数据测试了你的代码,它对我有用。发送到浏览器的选择的 html 是什么?

标签: asp.net-mvc razor html.dropdownlistfor


【解决方案1】:

在视图代码中未指定所选值,当您调用时:

   @Html.DropDownListFor(x => x.BranchID, 
                              new SelectList(Model.listofBranch, "BranchID", "BranchName"), 
                              new { @class = "form-control m-input", @id = "BranchID" })

没有传递给SelectList构造函数的值来指示SelectedValue

假设您要选择的值是保存到模型中的值,应该是这样的:

    @Html.DropDownListFor(x => x.BranchID, 
                               new SelectList(Model.listofBranch, "BranchID", "BranchName", Model.BranchID), 
                               new { @class = "form-control m-input", @id = "BranchID" })

【讨论】:

  • 感谢您的支持,但这并没有解决我的问题
  • 实际上我在 Model.BranchID 中有一个值,但仍未设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多