Pass Html String from Controller to View ASP.Net MVC

Which is the best way to pass the Html String block from Controller to View in MVC. I want it display that html block at the page load. Thank you. It can be any Html,
e.g

<table style="width:300px">
<tr>
  <td>Jill</td>
  <td>Smith</td> 
  <td>50</td>
</tr>
<tr>
  <td>Eve</td>
  <td>Jackson</td> 
  <td>94</td>
</tr>
</table>

I want to pass this as a string from controller to View. where it will be displayed as an html.

Thank you.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In your controller action :

ViewBag.HtmlStr = "<table style="width:300px"><tr><td>Jill</td><td>Smith</td> <td>50</td></tr><tr><td>Eve</td><td>Jackson</td><td>94</td></tr></table>";

Your view :

@Html.Raw(ViewBag.HtmlStr)

Method 2

You can assign the html in controller to ViewBag and access the ViewBag in View to get the value that is the html

Controller

ViewBag.YourHTML = htmlString;

View

<div> @ViewBag.YourHTML </div>

Its better to not to pass the html from controller to View rather pass the object or collection of object to View (strongly typed view) and render html in View as it is responsibility of View

Controller

public ActionResult YourView()
{
    //YourCode
    return View(entities.yourCollection.ToList());
}

Veiw

<table style="width:300px">
    foreach (var yourObject in Model)
    {
       <tr>
             <td>@yourObject.FirstName</td>
             <td>@yourObject.LasttName</td> 
             <td>@yourObject.Amount</td>
       </tr>      
    }

</table>

Method 3

Best approach will be to create a partial view and append the html returned by it in your parent view inside some container div.

In your main view do like this:

<div>

    @{

    Html.RenderAction("youraction","yourcontroller")

     }

</div>

in your action do this:

public ActionResult youraction()
{
 return View();
}

and your partial view:

@{
Layout = null;
}

<table style="width:300px">
<tr>
  <td>Jill</td>
  <td>Smith</td> 
  <td>50</td>
</tr>
<tr>
  <td>Eve</td>
  <td>Jackson</td> 
  <td>94</td>
</tr>
</table>

Method 4

Controller

 ViewBag.HTMLData = HttpUtility.HtmlEncode(htmlString);

View

@HttpUtility.HtmlEncode(ViewBag.HTMLData)

Method 5

You can use ViewBag.YourField or ViewData["YourStringName"] and for retreiving it in your View. Just place it where you want preceded by @ like this @ViewBag.YourField or @ViewData["YourStringName"].


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x