Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a utility method return raw html in MVC razor

I am trying to output a value to the page using MVC razor of autoplay='autoplay' in order to autoplay HTML5 video. My method GetAutoPlayVideo reads the web.config file to determine if the site will autoplay the videos.

public static string GetAutoPlayVideo()
{
     bool autoPlayVideo = Converter.ToBoolean(System.Web.Configuration.WebConfigurationManager.AppSettings["AutoPlayVideo"]);
     if (autoPlayVideo)
     return "autoplay='autoplay'";
     else
         return string.Empty;
}

Then on the page use the following markup:

    <div id="videoHolder">
                <video id="video" width="503" height="284" @Html.Raw(MyUtility.GetAutoPlayVideo()) controls >
                @foreach (string s in Model.SelectedShow.VideoFiles)
                {
                    <source src="@(CdnResources.GetImageUrl(s))" type="@(Utility.GetMimeType(s))" />
                }
                Your browser does not support the video tag.
            </video>
        </div>

The syntax I have created so far is this:

@Html.Raw(MyUtility.GetAutoPlayVideo())

is it possible to shorten this up to something like?

@MyUtility.GetAutoPlayVideo()
like image 621
Orin Avatar asked Dec 19 '12 16:12

Orin


1 Answers

Yes.

The Razor escaping system will not escape anything of type IHtmlString. The Html.Raw() method simply returns an HtmlString instance containing your text.

You can simply declare your method as returning IHtmlString, and call Html.Raw() (or new HtmlString() inside.

like image 109
SLaks Avatar answered Sep 21 '22 09:09

SLaks