【问题标题】:DropDownListFor generates 'The name 'model' does not exist in the current context' errorDropDownListFor 生成 'The name 'model' does not exist in the current context' 错误
【发布时间】:2019-06-04 03:07:45
【问题描述】:

刚开始使用 MVC3 并在尝试在视图中构建下拉菜单时遇到了问题。 ViewModel 填充了一个 SelectList 项:

mdm.CaptionSetList=new SelectList(CaptionSet.Fetch(), "CaptionSetId", "Description")

然后在视图中使用:

@Html.DropDownListFor(model => model.Entity.CaptionSetId, model.CaptionSetList) 

但是当页面被点击时,该行会用编译器消息突出显示:

编译器错误消息:CS0103:当前上下文中不存在名称“模型”

我犯了什么初学者的错误?

【问题讨论】:

    标签: asp.net-mvc-3 drop-down-menu razor


    【解决方案1】:

    DropDownListFor 的第一个参数是一个函数,所以这部分是正确的,但第二部分只是期待一个 SelectList,所以你需要做的就是

    @Html.DropDownListFor(model => model.Entity.CaptionSetId, Model.CaptionSetList) 
    

    注意大写。

    进一步说明

    在强类型视图中,Model 是一个属性,它引用绑定到视图的模型。由于第二个参数只需要一个列表,并且您已指定模型具有名为 CaptionSetList 的属性,因此您将列表指定为Model.CaptionSetList。如果您将列表放入ViewBag,您将放入ViewBag.CaptionSetList

    将此与第一个参数进行对比,第一个参数是一个函数,它接受一个与模型相同类型的参数。

    【讨论】:

      【解决方案2】:

      遇到同样的错误。

      就我而言,我进行了一些搜索和替换,却忘记更改 lambda 表达式:

      @Html.DropDownListFor(m => model.StagingDelegate.ManagerId, new[]{
                   new SelectListItem() {Text = "ManagerId 1", Value = "1"},
                   new SelectListItem() {Text= "ManagerId 2", Value= "2"},
                   }, "Choose a Manager", new { @class = "form-control form-control-sm " })
      

      将 m => 替换为 model =>:

      @Html.DropDownListFor(model => model.StagingDelegate.ManagerId, new[]{
                   new SelectListItem() {Text = "ManagerId 1", Value = "1"},
                   new SelectListItem() {Text= "ManagerId 2", Value= "2"},
                   }, "Choose a Manager", new { @class = "form-control form-control-sm " })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 2022-06-17
        • 2022-12-27
        • 1970-01-01
        相关资源
        最近更新 更多