Rafael Sanchez
Rafael Sanchez

Reputation: 414

How to Display string text in html body?

I'm just starting with ASP.NET, C# and HTML.

I want to display a text message in the browser if an email was sent successfully.

How do I show in the HTML body the value of a variable that was previously defined in the script part of the .aspx file?

<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>

Upvotes: 0

Views: 7696

Answers (2)

Georg Patscheider
Georg Patscheider

Reputation: 9463

First, define an unique id for the HTML element that serves as placeholder for your message

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

Then in your javascript, access the placeholder and insert HTML into it. I am using jQuery for this.

<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>

EDIT: this will not work for the scenario of OP, because this assumes that theResult is available as Javascript variable. But OP uses <script runat="server"> to execute C# code.

Upvotes: 0

Zay Lau
Zay Lau

Reputation: 1864

You may want to use the asp:Literal server control which it's syntax is: <asp:Literal runat="server" ID="LiteralText"/>

And assign text to it in code behind: LiteralText.Text = theResult;

Upvotes: 2

Related Questions