开发者

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?


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜