【问题标题】:T4MVC - Actions with model binding - how to get a fully qualified strongly-typed URL string to another Controller?T4MVC - 具有模型绑定的操作 - 如何将完全限定的强类型 URL 字符串获取到另一个控制器?
【发布时间】:2012-06-18 20:53:23
【问题描述】:

我正在运行带有 .Net 4.5 位和 T4MVC 的 Visual Studio 2012 RC。

我在我的AccountController 的 Action 方法中,我想为另一个看起来像这样的控制器生成一个完全限定的 URL;

public partial class ConfirmEmailController : Controller
{
    // ...

    [AllowAnonymous]
    [HttpPost]
    public virtual ActionResult Confirm(ConfirmEmailModel model)
    {
         //...
    }
    // ...
}

所以我想调用一个函数(当在我的 AccountController Action 方法中创建一个我可以通过电子邮件发送的链接时;

    private string GetEmailConfirmationUrl(MembershipUser aUser, bool confirm)
    {
        string code = aUser.ProviderUserKey.ToString();
        var model = new ConfirmEmailModel() { Code = code, Confirm = confirm };

        Url.Action(MVC.ConfirmEmail.Confirm(model); // very typesafe but doesn't work
    }

不过和这个其他成员的经历类似Strongly-typed T4MVC Action/ActionLink我只是简单的得到了模型类的名字"www.Models.ConfirmEmail"

我正在使用最新的 T4MVC 位,但自那篇帖子以来这里似乎没有任何变化。

我不一定希望能够构造和传递这样的模型,我只想以强类型、类型安全的方式构造一个完整的 URL。

我知道这行得通;

Url.Action(MVC.ConfirmEmail.Confirm().AddRouteValues(new ConfirmEmailModel() { Code = code, Confirm = confirm }));

但这不好,因为它不能验证我传入的模型参数是否对该控制器有效,我可以将它们传递给任何控制器(我已经犯了这个错误)。

有没有其他方法可以实现这一点,或者我必须在我的Confirm() 操作中添加一个参数列表?

【问题讨论】:

  • 令人费解的是,像 T4MVC 这样流行的项目不应该支持它。

标签: asp.net-mvc-3 visual-studio-2010 strong-typing t4mvc


【解决方案1】:

我认为你做不到。

如果您查看 T4MVC 生成的代码,您会发现没有任何东西可以“反转”模型绑定器中的逻辑。基本上 T4MVC 不知道正在使用模型绑定器。

编辑:

可以使用 T4MVC 生成 URL,但需要使用 T4 生成的重载。所以在你的情况下只是

Url.Action(MVC.ConfirmEmail.Confirm());

这足以生成 URL。参数的实际值将在运行时根据您的模型绑定创建。

【讨论】:

  • 很公平。我不一定要专门这样做。我真正想做的(根据标题)是从强类型代码生成一个完全限定的 URL。我会很高兴有任何可以让我这样做的解决方案。
  • 我不懂编辑。 Url.Action(MVC.ConfirmEmail.Confirm()); 几乎是 @cirrus 写的,除了参数 - 这就是它根本无法编译的原因。问题出在参数上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多