Home > Enterprise >  Cannot read C# object from view model while rendering cshtml
Cannot read C# object from view model while rendering cshtml

Time:09-27

I have the following class defined in View model

public class config{
    public string Name{ get; set;}
    public string HtmlContent{ get; set;}
}

An object of the above class is returned using view in Index.cs and rendered using Index.cshtml

public ActionResult Index()
     {
     config res = new config();
     
     res.Name = "John";
     res.HtmlContent = "<h1>Hi @Model.Name </h1>";
     
     return View(res);
     }

Index.cshtml:

<div id = "Header">@Html.Raw(@Model.HtmlContent)</div>

Output received:

Hi @Model.Name

Output Expected:

Hi John

Is there a way to read the C# object embedded inside the html tags?

CodePudding user response:

IMHO, it doesn't make much sense to try to cheat yourself. @Model is not html tag, it is a net view engine helper. Try this

public ActionResult Index()
{
            var model = new config();
            model.Name = "John";
            model.HtmlContent = $"<h1>Hi {model.Name} </h1>";

            return View(model);
}

it usually makes sense when you don't have any views in your project. For example, you can use it in your API controller

           var model = new config();
            model.Name = "John";
            var content = $"<h1>Hi {model.Name} </h1>";

            return new ContentResult()
            {
                Content = content,
                ContentType = "text/html",
            };

CodePudding user response:

List<config > cf = new List<config >()
{
  new config {name = "abc", HtmlContent = "abc"}
};
  • Related