skip to Main Content

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 ?

3

Answers


  1. 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>
    
    Login or Signup to reply.
  2. You only need to use @Model to replace @model:

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

    Update:
    Since you are using ViewBag in backend,here is a demo:

    Model:

    public class TestModel {
            public string firstName { get; set; }
            public string lastName { get; set; }
    
        }
    

    C# code:

    TesstModel model=new TestModel{firstName="f",lastName="l"};
    var text = "<h1> hello "+model.firstName+" "+model.lastName+" </h1>";
    
    Login or Signup to reply.
  3. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search