views:

68

answers:

1

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?

+1  A: 

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

Turnkey
sorry, do you have an example of this? I'm still pretty rookie when it comes to MVC
rockinthesixstring
I forgot to mention, the above code is being used in a UserControl and not in a regular View.
rockinthesixstring
Oh, and the Usecontrol is loaded in a masterpage that is used throughout the site.
rockinthesixstring
If it's on the MasterPage then you might want to consider RenderAction rather than RenderPartial that way it will have its own controller that you can pass in the custom ViewModel.http://blogs.intesoft.net/post/2009/02/renderaction-versus-renderpartial-aspnet-mvc.aspx
Turnkey
Isn't this similar to my UserMetaData in my Service Repository? I have a partial class for User that extends the default items.
rockinthesixstring
I did this very similar to your example above, however I used my custom User MetaData instead of building another UserViewModal.
rockinthesixstring
It can be done that way, it depends on how general that property is to your model's usage overall. Usually the view model is for things that are specific to the view.
Turnkey