views:

25

answers:

1

here is my view code:

<%=Model.HtmlData %>

here is my controller code:

    public ActionResult GetPage()
    {
        ContentPageViewModel vm = new ContentPageViewModel();
        vm.HtmlData = _htmlPageRepository.Get("key");
        return View(vm);
    }

my repository class basically queries a database table that has the fields:

id, pageName, htmlContent

the .Get() method passes in a pageName (or key) and returns the htmlContent value.

Right now i have just started this (haven't persisted anything to the db yet) so i am not doing any explicit encoding in my code now.

What is the best practice for where i need to do encoding (in the model, the controller, the view ??)

+2  A: 

Encoding is a concern of the view. You may have two very different displays using the same database, so often it isn't advisable to store the data in a state required by the specific view.

As a side note... If you are using .NET 4

<%: Model.HtmlData %>

Is the new

<%= Sever.HtmlEncode(Model.HtmlData) %>
Sohnee
Good answer, although I would also mention `HttpUtility.HtmlAttributeEncode()` in case you're sticking data in an attribute.
Jason
@Sohnee - i am editing and saving it to the db. so are you saying save directly without do any encoding on the persistence ??
ooo
Quick story - I worked somewhere where they encoded everything on the way in to the database to save processing (you encode it once on the way in - job done). The data was displayed on a website and all was well. They then added a new UI on top of the data, running within a kiosk - and it wasn't web based - so they ended up having to un-encode everything on the fly each time they wanted to display the data. If the UI requires a specific encode / fiddle, it should be responsible for doing it. The data shouldn't be polluted by this requirement. Hope this helps.
Sohnee