skip to Main Content

How can I submit an input of text type or a textarea which has HTML tags using .NET Blazor server-side approach?

When I submit an input of text type without HTML tags, the information submitted enters perfectly, but when I include some HTML tags in the input, the submitted text comes empty, how can I submit inputs with HTML tags?

Here is my HTML code:

<input type="text"
id="quill-result-body"
class="form-control"
required
@bind="BlogPost!.Body" />

As I mentioned, if the input does not have HTML tags, the submitted information located in BlogPost.Body comes perfect, but when I put some HTML tags, it comes empty.

Anyone can help me? Thanks in advance

2

Answers


  1. It is because by default implementation Blazor tries to prevent security attacks / issues. Here in this case directly taking input for HTML content may lead to Cross Site Scripting Attacks (XSS). Therefore, you get empty input value.

    But if there is requirement of HTML content to be displayed and is absolutely necessary. You may use the HtmlString type.You need to be more careful in handling and sanitizing the input properly. Though it is not a good practice to be taking HTML as input.

    <input type="text" id="quill-result-body" class="form-control" required @bind="@BlogPost!.Body" />
    @code {
        BlogPost BlogPost = new BlogPost();
        public class BlogPost
        {
            public HtmlString Body { get; set; }
        }
    }
    
    Login or Signup to reply.
  2. Here is the code of new page that works for me – just created new Blazor Server to try.

    @page "/html"
    
    <h3>Test HTML Page</h3>
    
    <EditForm Model="@EditModel" OnValidSubmit="SubmitForm">
        <input type="text"
               id="quill-result-body"
               class="form-control"
               required
               @bind="EditModel!.Body" />
    
        <div>@EditModel.Body</div>
    
        <input type="submit" class="btn btn-primary mt-2" value="Submit"/>
    </EditForm>
    
    @code {
        class BlogPost
        {
            public string Body { get; set; }
        }
    
        private BlogPost EditModel { get; set; } = new();
    
        private void SubmitForm()
        {
            Console.WriteLine(EditModel.Body);
        }
    }
    

    And here’s HTML input and Console output.

    HTML InputConsole Output

    What Blazor .NET version do you use?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search