Monday, June 12, 2017

Decode HTML tags of database text in View



Hello Readers, sometimes it happens that you have saved text value with HTML tags in the database and when you fetch it to the view, they appear at it is. To decode those HTML tags, we will use HtmlDecode method of HttpUtility class. This class resides in System.Web namespace.
To understand this concept, we will take very short example code. I am using Visual Studio 2015 IDE and ASP.NET MVC.
Here I am considering that you are aware of basic knowledge of creating controller and views in MVC.
Steps:
Open Visual Studio IDE, File Menu -> New option -> Project option.



Select ASP.NET Web Application under Web template.

Give a meaningful name to project as per your desire. Select location. Press OK button. 

Select MVC template. Press OK.


Go to your desired controller in which you have to work. For example, here I am taking HomeController.



Create an action method of any name. here I am giving name Index2.
The code is –
public ActionResult Index2()
        {
            ViewBag.msg = "This is <b> Bold </b> Text and color is <font color='red'><b>Red</b></font> ";
            return View();
        }
ViewBag is a dynamic property through which we can carry data from controller to view.
msg is a variable of ViewBag.
Here i have taken ViewBag for text containing HTML  tags. you will fetch data from database record and take into the view by using any method like Model property etc.
Right click on method name and Add view.


Choose Empty template and click on Add button


Code inside body tag of View-
<body>
    <div>
        @ViewBag.msg
        <br /><br />
        @Html.Raw(System.Web.HttpUtility.HtmlDecode(ViewBag.msg))
    </div>
</body>
Save the project and run it. You will get following output in the browser-

First message is without decoding and second one is with decoding.
I hope this article is helpful for you.
Happy coding.

Rudra Pratap Singh
Software Engineer
singhrudrapratap29@gmail.com
rudrapratapsingh29@rediffmail.com

How to Get Organic Views on Your Channel/Content

 Hi Friends, This post will be very short and specific in the information.  If you are a content creator and want some help in getting organ...