【问题标题】:How to Display string text in html body?如何在html正文中显示字符串文本?
【发布时间】:2016-09-08 09:44:32
【问题描述】:

我只是从 ASP.NET、C# 和 HTML 开始。

如果电子邮件发送成功,我想在浏览器中显示一条短信。

如何在 HTML 正文中显示先前在 .aspx 文件的脚本部分中定义的变量的值?

<script runat="server">    
    void SendAnEmail()
    {
        ...
        ...
        ...
        try
        {
            smtp.Send(message);
            string theResult = "Success! :)";
        }
        catch (System.Net.Mail.SmtpException)
        {
            string theResult = "Failure! :(";
        }            
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Send Mail</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        ??????
    </div>
    </form>
</body>
</html>

【问题讨论】:

  • 您确定要花时间学习这么古老的技术吗?为什么不使用 ASP.NET MVC?
  • @FrancescoLorenzetti84 这真的意味着'为什么你吃三明治,现在我们有披萨'
  • 更像是'你为什么要和奶奶调情,你的辣妹被打倒了'
  • @FrancescoLorenzetti84 尝试学习调情,你不能和辣妹直接和奶奶一起练习:)

标签: c# html asp.net


【解决方案1】:

您可能想要使用asp:Literal 服务器控件,它的语法是: &lt;asp:Literal runat="server" ID="LiteralText"/&gt;

并在后面的代码中为其分配文本: LiteralText.Text = theResult;

【讨论】:

【解决方案2】:

首先,为作为消息占位符的 HTML 元素定义一个唯一 id

<body>
    <div id="placeholderId"></div>
</body>

然后在您的 javascript 中,访问占位符并将 HTML 插入其中。我为此使用jQuery

<script type="javascript">
    function SendAnEmail() {
      // ...
      var theResult = 'some string';
      var placeholder = $('#placeholderId'); // jQuery selector by id
      placeholder.html(theResult); // set HTML content of placeholder element
    }
</script>

编辑:这不适用于 OP 的场景,因为这假定 theResult 可用作 Javascript 变量。但是OP使用&lt;script runat="server"&gt;来执行C#代码。

【讨论】:

  • 只是好奇,当&lt;script runat="server"&gt;theResult 设置在服务器端时,它是否可执行?
  • 实际上,这将是在客户端上运行的&lt;script type="javascript"&gt;。我没有注意到 OP 使用 &lt;script runat="server"&gt; 来运行 C# 方法“SendAnEmail”,所以我想这不起作用。
  • 请原谅我的无知,但是 JavaScript 与这里的任何事情有什么关系?使用 .NET 时,脚本是否总是用 JavaScript 编写的?
  • @Rafael 我读错了问题。您在服务器上使用 C# 发送电子邮件。我的回答只有在您从客户发送电子邮件时才有效,例如使用 AJAX。很抱歉造成混乱。
猜你喜欢
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 2019-09-13
相关资源
最近更新 更多