Search code examples
htmlasp.net-mvcrazorcontent-management-systemrazorengine

render the view using razorengine mvc


I am using RazorEngine to get the view and load it as html.but however my problem is I am reading html code from my database,and show it on my web page .but it gave me string result on my web page rather then html output. how can I solve this problem thank you in advace

My simple view like this

@model Cms.ViewModules.MasterPageViewModel
@Model.PageLanguageViewModel.HtmlCode

and this is how get the view as html from my views

 public static class HtmlHelperPageContent
    {
        public static IHtmlString GetPageAll(this HtmlHelper htmlHelper, MasterPageViewModelmodel)
        {

            string page = model.PageLanguageViewModel.SablonHtlmCodu;

            List<string> registeredModules = PageModulles.RegisteredModules;



            foreach (var modulename in registeredModules )
            {
                string fullmodulename = "${" + modulename + "}";
                if (page.Contains(fullmodulename ))
                {
                    string viewname = modulename.Insert(0, "PW_");

                    IHtmlString value = RenderViewHelper.RenderPartialToString("Views/Default/" + viewname + ".cshtml", model);

                    page=page.Replace(fullmodulename , value.ToHtmlString());
                }
            }

            return  MvcHtmlString.Create(page);


        }

RenderViewHelper class

public static class RenderViewHelper
    {
        public static IHtmlString RenderPartialToString(string viewPath, object model)
        {
            string viewAbsolutePath = MapPath(viewPath);

            var viewSource = File.ReadAllText(viewAbsolutePath);

            string renderedText = Razor.Parse(viewSource, model);
            return new MvcHtmlString(renderedText); 
        }
}

Solution

  • Another way would be to use IEncodedString (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Core/Text/IEncodedString.cs) instead of IHtmlString by creating a RawString (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Core/Text/RawString.cs) instance.

    @Raw does exactly that behind the scenes (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Core/Templating/TemplateBase.cs#L147).