简体   繁体   中英

How to pass an Html.Raw(x) as string parameter in a Mvc helper?

I am not sure that even the question is correct, so I am trying to explain what I want to achieve and hope you can help me with the best solution.

I am using in many places in my project the bootstrap modal, so I made an helper to make my life easier.

The helper is working with only one exception, I am not able to give the body content in the correct format.

The helper need 4 parameters to run:

@Html.MyModal(string bodycontent, string title, string closeBtnText, string id)

I have the bodycontent stored in the database like html, and I was planing to use this helper @Html.Raw(bodycontent) like this:

 @Html.MyModal(Html.Raw(model.Content).toString(), model.Title, resources.Close, model.Id)

Obviously is not working, still showing the content with html tags.

Here is the helper code which handle the bodyContent:

var bodyTag = new TagBuilder("div");
    bodyTag.MergeAttribute("class", "modal-body");
    bodyTag.MergeAttribute("style", "overflow-y: scroll;height:250px;");
    bodyTag.SetInnerText(bodycontent);

bodycontent is helper parameter, of type string.

Can you please help me with a solution in order to display the bodycontent like plain text (in database is stored like html)?

One solution to my problem, is:

  1. I changed the data type for bodycontent from string to IHtmlString
  2. I replace the following line in the helper:

    bodyTag.SetInnerText(bodycontent);

with:

 bodyTag.InnerHtml=bodycontent.ToHtmlString();

and now my helper is working as expected:

 @Html.MyModal(Html.Raw(model.Content), model.Title, resources.Close, model.Id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM