Search code examples
c#asp.net-mvcasp.net-mvc-routingmodelbinderst4mvc

custom model binder with T4MVC


I have a custom model binder in my MVC app but I don't know hos I can use T4MVC with it.

Usualy I would Call my action this way :

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

With T4MVC it should be like this :

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

But since T4 does'nt know about my binder, he try to send the object in the url but what I want is that he generate the url like this : Contract/{contractId}/Version/{action}/{version}

Also note that I have a custom route :

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

This is my binder :

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;
        }

What should I do? I don't want to have magic string in my route...

Thanks!


Solution

  • Try something like this:

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