C# 带有T4MVC的自定义模型绑定器
我的MVC应用程序中有一个自定义模型活页夹,但我不知道我可以用它来使用T4MVC 通常我会这样称呼我的行为:C# 带有T4MVC的自定义模型绑定器,c#,asp.net-mvc,asp.net-mvc-routing,modelbinders,t4mvc,C#,Asp.net Mvc,Asp.net Mvc Routing,Modelbinders,T4mvc,我的MVC应用程序中有一个自定义模型活页夹,但我不知道我可以用它来使用T4MVC 通常我会这样称呼我的行为: return RedirectToAction("Edit", "Version", new {contractId = contract.Id.ToString()}); 对于T4MVC,应如下所示: return RedirectToAction(MVC.Version.Edit(contract)); 但是由于T4不知道我的绑定器,他尝试在url中发送对象,但我想要的是他生成如
return RedirectToAction("Edit", "Version", new {contractId = contract.Id.ToString()});
对于T4MVC,应如下所示:
return RedirectToAction(MVC.Version.Edit(contract));
但是由于T4不知道我的绑定器,他尝试在url中发送对象,但我想要的是他生成如下url:Contract/{contracid}/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;
}
public覆盖对象BindModel(ControllerContext ControllerContext,ModelBindingContext bindingContext)
{
var construcd=GetValue(bindingContext,“construcd”);
var version=GetA(bindingContext,“version”);
var合约=_session.Single(constractd);
如果(合同==null)
{
抛出新的HttpException(404,“未找到”);
}
var user=_authService.LoggedUser();
if(contract.CreatedBy==null | | |!contract.CreatedBy.Id.HasValue | | | contract.CreatedBy.Id.Value!=user.Id)
{
抛出新的HttpException(401,“未授权”);
}
if(contract.Versions.Count<版本)
{
抛出新的HttpException(404,“未找到”);
}
退货合同;
}
我该怎么办?我不想在我的路线上有魔法线
谢谢 试试这样的方法:
return RedirectToAction(MVC.Version.Edit().AddRouteValues(new {contractId = contract.Id.ToString()}));
现在,同样的情况也可以通过以下方式实现。 您可以实现自定义解除绑定器:
public class ContractUnbinder : IModelUnbinder<Contract>
{
public void UnbindModel(RouteValueDictionary routeValueDictionary, string routeName, Contract contract)
{
if (user != null)
routeValueDictionary.Add("cityAlias", contract.Id);
}
}
之后,您通常可以使用MVC.Version.Edit(契约)生成URL
ModelUnbinderHelpers.ModelUnbinders.Add(new ContractUnbinder());