开发者

Detect Route Values in a View

开发者 https://www.devze.com 2023-01-31 10:07 出处:网络
Is it possible to detect a route value in a view? Such as /pages/create/1 and I want to check to see if 1 is there?

Is it possible to detect a route value in a view?

Such as /pages/create/1 and I want to check to see if 1 is there?

Basically, I wan开发者_Go百科t to render a different partial view based on this value though I'm fairly sure this is probably not the best way to go about what I'm trying to achieve.

On a side note, instead of doing the above is it possible for me to be able to change what partial views are rendered in a view based on a value from within my controller?


ViewContext.RouteData.Values["whatever"]


You can inspect a RouteData object through ViewPage.ViewContext.RouteData. Then check for values using something like

string areaname = routeData.Values["area"] as string;
string controllername = routeData.Values["controller"] as string;
string actionname = routeData.Values["action"] as string;
string id = routeData.Values["id"] as string;

If you find that you want to inspect these values in the controller instead, you can access them using ControllerBase.ControllerContext.RouteData. Something similar applies for action filters etc.


Other answers are correct, but thought i'd address your last sentence:

On a side note, instead of doing the above is it possible for me to be able to change what partial views are rendered in a view based on a value from within my controller?

Well partial view's are rendered in the View itself (unless calling from JavaScript and binding directly to DOM) with the following code:

<%: Html.RenderPartial("SomePartial") %>

So to prevent "code soup" (if statements) in your view, you use a HTML helper which calls through to RenderPartial after inspecting the ViewContext:

public static string RenderCustomPartial(this HtmlHelper helper, RouteData rd)
{
   string partialName;

   if (rd.Values["SomeParam"] == 1)
     partialName = "PartialOneName";
   else
     partialName = "PartialTwoName";

   return helper.RenderPartial(partialName);
}

And then in the View:

<%: Html.RenderCustomPartial(ViewContext.RouteData) %>

You could make some mods to the above - like access the route data directly in the extension, pass through the model to bind in the partial, etc - but you get the idea.

Alternatively you could do the above IF statement in your controller, and stuff the partial view name in the ViewData, then use that in the regular RenderPartial call in your View.

Whatever floats your boat. :)

0

精彩评论

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