代码之家  ›  专栏  ›  技术社区  ›  George Mauer

为什么HTML助手不输出这个ASP MVC视图中的任何内容?

  •  1
  • George Mauer  · 技术社区  · 15 年前

    下面是我的ASP MVC视图。请注意,它有一个包含简单表单的DIV。我正在使用html.textbox()尝试输出输入元素,但没有输出。表单呈现得很好,但是在我希望看到输入标记的地方什么也没有。

    我肯定这是一个初学者的错误,但我做错了什么?

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" 
        Inherits="System.Web.Mvc.ViewPage" %>
    <%@ Import Namespace="gnodotnet.Web.Controllers" %>
    
    <asp:Content ID="indexContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
        <div id="sponsorsContainer" class="container" style="width: 110px; float: left; height:482px; margin-right: 20px;"> &nbsp; </div>
        <div id="calendarContainer" class="container" style="width: 500px; height: 482px; float: left;"> &nbsp;
            <iframe src="http://www.google.com/calendar/embed?height=462&amp;wkst=1&amp;bgcolor=%23FFAD57&amp;src=ck1tburd835alnt9rr3li68128%40group.calendar.google.com&amp;color=%23AB8B00&amp;ctz=America%2FChicago" style=" border-width:0 " width="482" height="462" frameborder="0" scrolling="no"></iframe>
        </div>    
        <div id="mailingListContainer" class="container" style="width: 95px; float: left; height:182px; margin-left: 20px;"> 
            <% using (Html.BeginForm()) { %>
                <%= Html.AntiForgeryToken() %>
               <h4>Subscribe to our Mailing List</h4>
               Name: <% Html.TextBox("subscribeName"); %>
               Email: <% Html.TextBox("subscribeEmail"); %>
               <% Html.Button("subcribeOk", "Subscribe", HtmlButtonType.Submit); %>
           <% } %>
        </div>
    </asp:Content>
    
    2 回复  |  直到 14 年前
        1
  •  5
  •   spender    15 年前

    使用

    <%=Html.TextBox
    

    而不是

    <% Html.TextBox
    

    <%=相当于response.write,而<%仅打开代码块。

        2
  •  1
  •   JoshJordan    15 年前

    检查 HtmlHelper 方法。一些,例如 RenderPartial 返回 void . 这些是内部使用的 Response.Write() 或者另一种直接将一些HTML输出到响应steream的方法。

    因此,它们可以在执行任何内联代码的ASP代码块中使用,如:

    <% Html.RenderPartial("SubsciberProfile") %>
    

    但是,大多数内置表单方法,例如 Html.TextBox 返回A string . 在这些情况下,必须执行代码 发送到响应。如果你用过

    <% Html.TextBox("subscriberEmail") %>
    

    然后文本框HTML将作为 一串 立即丢弃。它相当于做这样的事情:

    string name = "John Doe";
    name.Replace("Doe","Smith");
    

    注意返回的值 Replace 从未分配给任何内容,因此对方法进行评估,但从未使用其返回值。

    相反,我们必须使用这样的方法:

    <%= Html.TextBox("subscriberEmail") %>
    

    注意等号!这意味着代码块应该 输出 方法的结果。如上所述, <%= someString %> <% Response.Write(someString) %> . 这是微妙的,但要记住非常重要。