Orin
Orin

Reputation: 371

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()

Upvotes: 10

Views: 8551

Answers (1)

SLaks
SLaks

Reputation: 887767

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.

Upvotes: 16

Related Questions