1

I'm new to razor and display templates so please correct me where I'm wrong. I'm working with a string that contains HTML. If I try converting it directly to a HtmlString, my Ajax form refuses to submit. As a workaround I tried to use Display templates with the goal of achieving something like this

My @foreach loop contains this

 @Html.DisplayFor(modelItem => myModel.myString, "HtmlString")

My DisplayTemplate contains this

HtmlString.cshtml

@model String

@{
    new HtmlString(@Model);
}

So if myString = "<ul><li>my text</li></ul>"

I would like my ajax form to display

  • my text

What I have now doesn't work and returns nothing. Please help with what I'm doing wrong.

Community
  • 1
  • 1
usr4896260
  • 1,427
  • 3
  • 27
  • 50

2 Answers2

1

You should use @Html.Raw() like;

@Html.Raw(Model.myString)

Hope this helps.

Qsprec
  • 265
  • 3
  • 11
  • Do you mean to use `@Html.Raw(Model.myString)` in `HtmlString.cshtml` ? Because I tried using this in my View and the Ajax form refused to submit. – usr4896260 May 10 '16 at 22:01
  • 1
    @usr4896260. Using `Html.Raw()` is correct. But this has nothing to do with your Ajax form. If you have a problem with that, then you should show the relevant code. –  May 10 '16 at 22:43
0

I have made some minor modifications to your code. Please test and implement.

In your HtmlString.cshtml file, replace your code with the following. This is a partial view that is being called in a foreach loop and is passed a string value that contains HTML. @Html.Raw is used to displayed the HTML as HTML:

@model String

@Html.Raw(Model)

Your view will receive a list of strings that is passed from your controller's action method. Each string contains the HTML:

@model List<string>

@foreach (var s in Model)
{
     @Html.Partial("HtmlString", s)
}

This is the data that I used to test your scenario. The HTML that is outputted is correct:

public ActionResult TestMethod1()
{
     List<string> strings = new List<string>();

     strings.Add("<ul><li>my text</li></ul>");
     strings.Add("<ul><li>my text</li></ul>");

     return View(strings);
}

The resulting output looks like this:

<ul><li>my text</li></ul><ul><li>my text</li></ul>

I hope that I understood your question correctly?

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234