Home > Enterprise >  how to render html text in ASP.NET nshtml and Razor if it has model values
how to render html text in ASP.NET nshtml and Razor if it has model values

Time:01-10

I have a variable with html text and model values

var text = "<h1> hello @Model.firstName @Model.lastName </h1>"

and in cshtml I have

@Html.Raw(text) 

my code looks like

    @model TextModel
@{
     var text = Viewbag.text
 }
 ...
 <div>
      @Html.Raw(text)
 </div>

what it renders is "hello @model.firstName @model.lastName" but what I want is "hello Jack James" I don't know what can I do ?

CodePudding user response:

You could do this:

var text = $"<h1> hello {Model.firstName} {Model.lastName} </h1>";

and then: @Html.Raw(text)

Edited: Not sure what your CSHTML looks like, but it should work (providing it looks something like this):

@model YourModel
@{
     var text = $"<h1> hello {Model.firstName} {Model.lastName} </h1>";
 }
 ...
 <div>
      @Html.Raw(text)
 </div>

CodePudding user response:

You only need to use @Model to replace @model:

var text = "<h1> hello @Model.firstName @Model.lastName </h1>"

CodePudding user response:

I would recommend manipulating the string before you pass it to the view.

Controller:

{
    //inside of the get function
    var person = //call to get the data
    var text = $"<h1> hello {person.firstName} {person.lastName} </h1>"
    //add `text` to the viewbag

}

View:

<div>
    @Html.Raw(Viewbag.text)
</div>
  • Related