Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 626
Pratik Bhoir Avatar asked Sep 07 '25 17:09

Pratik Bhoir


2 Answers

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)
like image 155
kvothe Avatar answered Sep 11 '25 00:09

kvothe


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>
like image 41
Adil Avatar answered Sep 10 '25 23:09

Adil