How to Bind HTML Content To Div in Asp.Net Core 8 MVC In C#.Net

How to display or bind the HTML tag or string into div control in asp.net core 8 mvc using c#.net. @Html.Raw() in view to display HTML, controller.
In this article I will show you how you can bind the HTML tag content into a div control in asp.net core 8 mvc (.net core 6, .net core 7) application in view passed from controller into a model class property using c#.net.

Now for this article first we will create a new asp.net core 8 mvc application with C#.Net. Now add a model class file as shown below. 

namespace Project.Models
{
    public class UserModel
    {
        public string ProfileComment { get; set; }
    }
}
After adding model class code. We need to add a controller and assign some html code to the property. For this we will use little bit C#.Net code to prepare the html tag. Here we will pass the value in the page load (HttpGet). Please check the below code.
        [HttpGet]
        public IActionResult Index()
        {
            UserModel userModel = new UserModel();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 5; i++)
            {
                sb.Append("<div><b>Comment " + i + "</b>: This is a test <i>comment</i>.<br/></div>");
            }
            userModel.ProfileComment = sb.ToString();
            return View(userModel);
        }
In above code I have taken StringBuilder object to prepare the html string.  After preparing the html tags string I have assign it to model property 'ProfileComment'. Now we will create a view, and add the below code into it. 
@model UserModel
@{
    ViewData["Title"] = "Home Page";
}
<h2>HTML Content Display</h2>
<br />
<div>@Model.ProfileComment</div>
In above code I have used @Model.ProfileComment to display the model value. Now lets run ad check the output.

bind HTML Content To div in Asp.Net Core 8 MVC In C#.Net
Here we are having all html content prepared at controller end. Now press F5 to check the final output.

Display HTML Content To div in Asp.Net Core 8 MVC In C#.Net
Here in above output simply the Html content ius getting displayed instead of displaying in rich formatted value. Now we will make some changes in code to display it correctly. We will user @Hrml.Rwa() to display the value is rich format.
@model UserModel
@{
    ViewData["Title"] = "Home Page";
}
<h2>HTML Content Display</h2>
<br />
<div>@Html.Raw(Model.ProfileComment)</div>
In above code just check the highlighted code. By using |@Html.Raw() in will make the html text display in rich format. 
How to bind HTML Content To div in Asp.Net Core 8 MVC In C#.Net

Post a Comment