2

我的 MVC 应用程序中有一个自定义模型绑定器,但我不知道是否可以使用 T4MVC。

通常我会这样称呼我的行动:

return RedirectToAction("Edit", "Version", new {contractId = contract.Id.ToString()});

使用 T4MVC 它应该是这样的:

return RedirectToAction(MVC.Version.Edit(contract));

但由于 T4 不知道我的活页夹,他尝试在 url 中发送对象,但我想要的是他生成这样的 url:Contract/{contractId}/Version/{action}/{version}

另请注意,我有一个自定义路线:

routes.MapRoute(
                "Version", // Route name
                "Contract/{contractId}/Version/{action}/{version}", // URL with parameters
                new { controller = "Version", action = "Create", version = UrlParameter.Optional } // Parameter defaults
            );

这是我的活页夹:

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var contractId = GetValue(bindingContext, "contractId");
            var version = GetA<int>(bindingContext,"version");

            var contract = _session.Single<Contract>(contractId);
            if (contract == null) 
            {
                throw new HttpException(404, "Not found");
            }
            var user = _authService.LoggedUser();
            if (contract.CreatedBy == null || !contract.CreatedBy.Id.HasValue || contract.CreatedBy.Id.Value != user.Id)
            {
                throw new HttpException(401, "Unauthorized");
            }

            if (contract.Versions.Count < version)
            {
                throw new HttpException(404, "Not found");
            }
            return contract;
        }

我该怎么办?我不想在我的路线中有魔术字符串......

谢谢!

4

2 回答 2

3

尝试这样的事情:

return RedirectToAction(MVC.Version.Edit().AddRouteValues(new {contractId = contract.Id.ToString()}));
于 2011-04-18T04:56:48.503 回答
1

现在同样可以使用ModelUnbinders来实现。您可以实现自定义解绑器:

public class ContractUnbinder : IModelUnbinder<Contract>
{
    public void UnbindModel(RouteValueDictionary routeValueDictionary, string routeName, Contract contract)
    {
        if (user != null)
            routeValueDictionary.Add("cityAlias", contract.Id);
    }
}

然后在 T4MVC 中注册它(来自 Application_Start):

ModelUnbinderHelpers.ModelUnbinders.Add(new ContractUnbinder());

之后,您通常可以使用 MVC.Version.Edit(contract) 生成 url。

于 2012-08-20T06:29:23.490 回答