Search code examples
htmltextareabindblazor

Blazor bind html to textarea


This seems simple but I haven't been able to find an answer. In my Blazor Server side program I have a popup email form that I pre-populate with text and the user can then edit it and click send for the program to send the email. If the user enters line breaks in the textarea they come back as \n and that is fine. However I have been unable to send text to the textarea with line breaks.

In the popup form I have:

        <div class="form-group-sm">
            <label class="control-label">Message</label>
            <textarea rows="4" @bind="EmailMessage" class="form-control"></textarea>
        </div>

If I send

EmailMessage = "Test Email text \\nline two <br /> line 3";

I get enter image description here

If I send

EmailMessage = Markdown.ToHtml("Test Email text \\nline two <br /> line 3");

I get enter image description here

Is it possible to send line breaks to a textarea bound to a property that the user then can edit and send the text back to the program?

Ideally this would be for any html markup but for now I'll settle for line breaks.


Solution

  • This is basic...you can augment it in many ways:

    @page "/"
    
    <div class="form-group-sm">
        <label class="control-label">Message</label>
        <textarea rows="4" value="@EmailMessage" @onchange="@((args) => EmailMessage = args.Value.ToString())" class="form-control"></textarea>
    </div>
    
    <button @onclick="@(()=>{})">Refresh</button>
    
    
    
    @code {
        private string emailMessage = "Test Email text \r\nline two \r\n line 3";
        
        public string EmailMessage
        {
            get =>  emailMessage;
            set
            {
                if (emailMessage != value)
                {
                    emailMessage = ((MarkupString)value).ToString();
                }
            }
    
        }
     
    }