【问题标题】:How to bind a value to a text box in MVC如何将值绑定到 MVC 中的文本框
【发布时间】:2015-10-28 08:18:37
【问题描述】:

当我想将模型中的值绑定到文本框时遇到问题,这是我的 MVC 视图代码:

@Html.TextBox("SellerBroker", model => model.OutOfMarket.BuyerBroker.Name , new { @class = "control-label" })

我希望我的文本框有一个名称或“SellerBroker”,它的价值来自我的模型属性model => model.OutOfMarket.BuyerBroker.Nameclass = "control-label" 的HTML 属性。但是,我收到以下错误:

无法将 lambda 表达式转换为类型“对象”,因为它不是委托类型

【问题讨论】:

  • @Html.TextBox("SellerBroker", Model.OutOfMarket.BuyerBroker.Name , new { @class = "control-label" }) 但你为什么要这样做而不是绑定到你的属性 - @Html.TextBoxFor(m => m.OutOfMarket.BuyerBroker.Name , new { @class = "control-label" })

标签: asp.net-mvc model-view-controller textbox


【解决方案1】:

@Html.TextBox() 可用于生成具有初始值的文本框(单向绑定)。

如果您想真正将文本框绑定到您的类属性(两种方式绑定),您应该使用@Html.TextBoxFor() 助手。此方法将 lambda 表达式作为参数,如您的示例中使用的那样。

您可以在以下位置找到有关 TextBox 助手的更多详细信息:Html.Textbox VS Html.TextboxFor

【讨论】:

    【解决方案2】:

    Helper @Html.TextBox() 不包含具有 lambda 参数的重载。你应该在没有 lambda 的情况下使用它,就像 @Stephen Muecke 建议你:

    @Html.TextBox("SellerBroker", Model.OutOfMarket.BuyerBroker.Name , new { @class = "control-label" })
    

    如果你想使用 lambda,你应该使用 @Html.TextBoxFor() 助手。但是你应该像这样更改名称:

    @Html.TextBoxFor(model => model.OutOfMarket.BuyerBroker.Name, new { Name = "SellerBroker", @class = "control-label"})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-03
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多