开发者

Asp.Net MVC Routes - Handle Multiple routes with the same signature?

I'm interested to know how people handle the following situation.

Assume we have a DataField and each DataField can have unlimited number of DataValues

We have 2 controllers to handle the manipulation of these objects

  • DataFieldController
  • DataValueContoller

Now if we ever need to add a new DataValue we need to know the ID of the CustomDataField. The following URL would be used,

/CustomDataValue/Add/1 

1 = DataField ID

However, because the ASp.Net MVC engine binds the parameter name to the model (IE in the case below. My DatValeu Object would have its ID replaced, when I am actually trying to pass through the FieldID)

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Site", action = "Home", id = UrlParameter.Optional } // Parameter defaults
    );

How can we handle this? Doing the following obviously will not work.

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with param开发者_开发百科eters
    new { controller = "Site", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{fieldid}", // URL with parameters
    new { controller = "Site", action = "Home", fieldid = UrlParameter.Optional } // Parameter defaults
);

I assume this is a common problem, I just cant find the obvious solution at the moment. It would be ok if the Signature was differant but both are /String/String/Int

==========================

How can these routes work then?

  • /DataValue/Add/{DataFieldID}
  • /DataValue/Edit/{ID}
  • /DataValue/List/{DataFieldID}

Must I add 3 routes?


Use constraints in routes like this:

routes.MapRoute(
    "Default", // Route name
    "CustomDataValue/{action}/{fieldid}", // URL with parameters
    new { controller = "Site", action = "Home", fieldid = UrlParameter.Optional } // Parameter defaults
);

It makes sure only URLs starting with "CustomDataValue" calls this route. It's declared as a constant, different from the default route. Make sure these specified routes are declared before the default route. Since there are no restrictions, all URLs are matched to it.

Update

I guess you have to call DataValueController methods with URLs like http://domain.com/CustomDataValue/Add/23. If that's the case use the following route:

routes.MapRoute(
    "CustomData", // Route name
    "CustomDataValue/{action}/{fieldid}", // URL with parameters
    new { controller = "DataValue", action = "List", fieldid = UrlParameter.Optional } // Parameter defaults
);

This will work if you have action methods in DataValueController named List/Add/Edit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜