asp.net-mvc-2html-helperpartial-viewsactionlink

Proper way of building MVC ActionLink


I've got an MVC ActionLink like so (which works just fine)

<%: Html.ActionLink(user.UserName, "Details", "Users", New With{.id = user.ID, .slug = Replace(user.UserName," ","-")}, nothing)%>

But since it's not "recommended" to do string manipulation in the View, I'm wondering how I could build a custom Html ActionLink to do the string replacement for me?


Solution

  • The custom ActionLink seems to be the wrong place to do it as well, better to pass the Slug via a custom View Model to the view from the controller. The Slug could be a property on the View Model and the string logic invoked in the setter.

    For example add a UserViewModel class to a "ViewModels" folder.

    public class UserViewModel
    {
      public User User { get; private set; }
      public string Slug { get; private set; }
    
      public UserViewModel(User user)
      {
          Slug = Replace(user.UserName," ","-");
      }
    }
    

    Then in the controller, pass it to the view as:

    return View(new UserViewModel(user))
    

    For more on ViewModel usage:

    MVC View Model Patterns