构建 MVC ActionLink 的正确方法

发布于 2024-09-08 23:16:11 字数 271 浏览 1 评论 0原文

我有一个像这样的 MVC ActionLink (效果很好)

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

但是由于不“建议”在视图中进行字符串操作,我想知道如何构建一个自定义 Html 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宛菡 2024-09-15 23:16:11

自定义 ActionLink 似乎也是错误的地方,最好通过自定义视图模型将 Slug 从控制器传递到视图。 Slug 可以是视图模型上的属性以及 setter 中调用的字符串逻辑。

例如,将 UserViewModel 类添加到“ViewModels”文件夹中。

public class UserViewModel
{
  public User User { get; private set; }
  public string Slug { get; private set; }

  public UserViewModel(User user)
  {
      Slug = Replace(user.UserName," ","-");
  }
}

然后在控制器中,将其传递给视图:

return View(new UserViewModel(user))

有关 ViewModel 用法的更多信息:

MVC 视图模型模式

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文