user1352057
user1352057

Reputation: 3182

MVC - How to render a 'a href' link in a View that's been stored in a database?

Question background:

I have an MVC4 app whos homepage data is supplied from a View Model.

The Issue:

Within the View Model I have a property called AboutUsDescOne This is set from the Controller and Action Method from data that has been retrieved from a database. Within the data set on the property is a a href link, The following shows the text stored in the database:

This is the website Google <a href="https://google.com/">Google</a> click the link.

The issue I'm having is when I render the data in the View the a href is being seen as text in the View and is not showing as a link, as shown:

enter image description here

The Code:

The propety is simply set as a propety on a standard ViewModel:

public string AboutUsDescOne {set; get;}

This is how it is then rendered in the View:

<div class="col-md-8 form-group">
   <p>
      <h4>@Model.HomePageVM.AboutUsDescOne</h4>
   </p>
</div>

Can anyone tell me how to get the link to render in the View?

Upvotes: 0

Views: 683

Answers (1)

Brad C
Brad C

Reputation: 2982

Try this:

<h4>@Html.Raw(Model.HomePageVM.AboutUsDescOne)</h4>

Use this helper with caution though. If a user can edit this block of HTML then you might be making yourself vulnerable to an XSS attack:

Text output will generally be HTML encoded. Using Html.Raw allows you to output text containing html elements to the client, and have them still be rendered as such. Should be used with caution, as it exposes you to cross site scripting vulnerabilities.

Upvotes: 1

Related Questions