darasd
darasd

Reputation: 2977

How do I automatically include a segment in a url with Asp.Net MVC

Say I have 3 versions of a website: A, B and C. I want my urls to be of the form:

{siteType}/{controller}/{action}/{id}

where siteType equals a, b or c.

When the user is in the A version of the website, then they should stay there; therefore all generated urls should have a siteType of a. Similarly for B and C.

I don't want to have to explicitly specify the siteType when generating urls - I want it generated automatically. Furthermore, the siteType parameter will only ever be used in one place - the overrided RenderView method in a base controller class - which will use the siteType parameter to pick out the correct view, css etc for that version of the website. I therefore have no interest in the siteType appearing as an argument to my actions. Only the RenderView method requires access to it.

What is the best way to achieve this?

Upvotes: 1

Views: 277

Answers (2)

griti
griti

Reputation: 650

We have almost the same with the site language (snippet from our global.asax.cs):

routes.MapRoute(
            "DefaultLanguage",
            "{lang}/{controller}/{action}/{id}",
            new { lang = "de-CH", controller = "Home", action = "Index", id = "" }
        );

Whenever no language is set the language will be set to swiss-german in our case.

Any actionlink will have the language code automatically from the current site. So we don't have to specify any language on Actionlinks.

Changing the siteType is simple, just add routeValues to your actionlink. e.g.

 <%= Html.ActionLink("Linktext", "Action", "Controller", new { siteType = "b" } %>

Upvotes: 1

MarkKGreenway
MarkKGreenway

Reputation: 8754

I may be quite off base but what it sounds like to me is a mobile site a-la

http://weblogs.asp.net/mschwarz/archive/2007/11/26/mvc-framework-and-mobile-device.aspx

public class MobileCapableWebFormViewEngine : WebFormViewEngine { public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { ViewEngineResult result = null; var request = controllerContext.HttpContext.Request;

    // Avoid unnecessary checks if this device isn't suspected to be a  mobile device
    if (request.Browser.IsMobileDevice)
    {
        result = base.FindView(controllerContext, "A/" + viewName, masterName, useCache);
    }

    //Fall back to desktop view if no other view has been selected
    if (result == null || result.View == null)
    {
        result = base.FindView(controllerContext, viewName, masterName, useCache);
    }

    return result;
} }

You could also instead of

Request.Browser.IsMobileDevice

have

Request.ServerVariables["URL"].Contains("A")

Upvotes: 0

Related Questions