【问题标题】:Html.LabelFor and Html.TextBoxFor generate empty html codeHtml.LabelFor 和 Html.TextBoxFor 生成空的html代码
【发布时间】:2018-05-22 13:39:16
【问题描述】:

我正在编写我的第一个 ASP.NET MVC 应用程序,但我遇到了一个大问题。我想制作一个代表表单的控件,但是当我尝试生成标签和文本框时,它返回给我一个空白页面。

所以,这是我的 model 文件 (MyModel.cs):

namespace MyNamespace.Models
{
  public class MyModel
  {
    [Required(ErrorMessage = "You have to fill this field")]
    [DisplayName("Input name")]
    public string Name{ get; set; }
  }
}

这是带有我的控件的 MyFormControlView.ascx 文件:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.MyModel>"%>
<div>
    <%
        using (Html.BeginForm())
        {
            Html.LabelFor(m => m.Name);
            Html.TextBoxFor(m => m.Name);
            Html.ValidationMessageFor(m => m.Name);
        }
    %>
</div>

这是我渲染控件的 Index.aspx 文件:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Main.Master" Inherits="System.Web.Mvc.ViewPage<System.Collections.IEnumerable>" %>

<asp:Content runat="server" ID="MainContent" ContentPlaceHolderID="MainContent">
This is my control test!
<%Html.RenderPartial("MyFormControlView", new MyNamespace.Models.MyModel { Name = "MyTestName"}); %>
</asp:Content>

所以,当我运行我的应用程序时,结果是孤独的标题:“这是我的控制测试!”并且生成的页面上没有标签或文本框。 如果我检查生成页面的源代码,我可以看到我的 &lt;div&gt; 块,但它的内部文本是空的。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    这些方法使用生成的 HTML 代码返回字符串。
    您没有对它们的返回值做任何事情。

    您需要在页面上使用@ 符号打印返回值:

    <%= Html.LabelFor(m => m.Name) %>
    

    请注意,由于这些不是语句,因此不应有 ;。在您的示例中,; 是无害的(它被解析为空的 C# 语句);如果它位于 HTML 标记内,它会在 HTML 源代码中打印 ;

    【讨论】:

    • 您的代码对我不起作用,它返回错误“需要分号”。但我想这是因为我使用的是 ASPxView 引擎而不是 Razor。我发现解决方案取决于您的代码: m.Name) %> - 这对我有用。谢谢!
    • @Ceridan:你是对的;我以为您使用的是 Razor。固定。
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多