Search code examples
asp.net-mvcasp.net-mvc-2asp.net-mvc-3html-helper

ASP.NET MVC 3 Custom HTML Helpers- Best Practices/Uses


New to MVC and have been running through the tutorials on the asp.net website.

They include an example of a custom html helper to truncate long text displayed in a table.

Just wondering what other solutions people have come up with using HTML helpers and if there are any best practices or things to avoid when creating/using them.

As an example, I was considering writing a custom helper to format dates that I need to display in various places, but am now concerned that there may be a more elegant solution(I.E. DataAnnotations in my models)

Any thoughts?

EDIT:

Another potential use I just thought of...String concatenation. A custom helper could take in a userID as input and return a Users full name... The result could be some form of (Title) (First) (Middle) (Last) depending on which of those fields are available. Just a thought, I have not tried anything like this yet.


Solution

  • Well in the case of formatting the DisplayFormat attribute could be a nice solution:

    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
    public DateTime Date { get; set; }
    

    and then simply:

    @Html.DisplayFor(x => x.Date)
    

    As far as truncating string is concerned a custom HTML helper is a good solution.


    UPDATE:

    Concerning your EDIT, a custom HTML helper might work in this situation but there's also an alternative approach which I like very much: view models. So if in this particular view you are always going to show the concatenation of the names then you could define a view model:

    public class PersonViewModel
    {
        public string FullName { get; set; }
    }
    

    Now the controller is going to query the repository to fetch the model and then map this model to a view model which will be passed to the view so that the view could simply @Html.DisplayFor(x => x.FullName). The mapping between models and view models could be simplified with frameworks like AutoMapper.