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.

2 Answers 2

1

You should use @Html.Raw() like;

@Html.Raw(Model.myString)

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

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. 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.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.