2011-04-16 131 views
2

我在我的MVC應用程序中有一個自定義模型綁定器,但我不知道我可以使用T4MVC它。T4MVC自定義模型綁定器

Usualy我會叫我的動作是這樣的:

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

隨着T4MVC它應該是這樣的:

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

但由於T4一點兒也不瞭解我的粘合劑,他嘗試發送在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; 
     } 

我該怎麼辦?我不想在我的路線中有魔法字符串...

謝謝!

回答

3

嘗試這樣:

return RedirectToAction(MVC.Version.Edit().AddRouteValues(new {contractId = contract.Id.ToString()})); 
1

現在同樣可以用ModelUnbinders(在http://t4mvc.codeplex.com/documentation 3.1)來實現。 你可以實現自定義unbinder:

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(合同),用於生成的URL。