开发者

Attribute that instructs standart string template to display string as plain HTML

For displaying/editing forms I use Html.DisplayForModel(). Whether there is native ASP.NET MVC attribute that can instruct standart string template to display model property with type of string as plain html, 开发者_开发技巧or I need to create my own attribute and change standart string template to apply this behavior? I don't want to crush Html.DisplayForModel() expression and use Html.Raw():

@Html.DisplayFor(m => m.Id)
@Html.DisplayFor(m => m.Title)
@Html.DisplayFor(m => m.DateCreated)
@Html.Raw(Model.Comment)

public class MyModel
{
public int Id {get;set;}
public string Title {get;set;}
public DateTime DateCreated {get;set;}
public string Comment {get;set;} // contains plain html
}


You could define a special display template for this property ~/Views/Shared/DisplayTemplates/Unencoded.cshtml:

@model string
@Html.Raw(Model)

and then in your view model use the [UIHint] attribute:

public class MyModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime DateCreated { get; set; }

    [UIHint("Unencoded")]
    public string Comment { get; set; } // contains plain html
}

Now your main view could simply look like this:

@model MyModel
@Html.DisplayForModel()

By using the Html.Raw helper you certify that you fully realize the consequences of this and that your site becomes vulnerable to XSS attacks and that you take adequate actions to avoid them.


You could create the display template of comments (place view into DisplayTemplates folder)

//sample comments.cshtml

@model MyApplicationNamespace.ViewModels.Comments

<ul>

@if (Model != null)
{
   for (int i =0; i<Model.Count(); i++ )
       {
           <li>Model.UserName + ":" + Model.CommentText </li>
       }
}

</ul>

And from now on, your comment will be rendered with this template. If you use built in autogenerating templates with @Html.DisplayForModel(), the properties of Comment type will be automatically rendered with this template, otherwise, use DisplayFor as with id, title, dateCreated cases

@Html.DisplayFor(m => m.Comments)

Html.DisplayFor return MvcHtmlString, and it is not html encoded any more

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜