I’m trying to wrap my head around MVC.NET 3.
I use a _Layout.cshtml as base (structure, navigation). As part of the layout I want to display two links used for changing language/localization.
These should be displayed and clickable no matter what page is viewed, and after changing the localization I want to reload the view that called the action. So the page that the customer is looking at will be reloaded, with new localization set.
One way is to copy and paste the localization-changing action in each of the sites controllers, but is there no easier and more elegant way?
I tried creating a specific controller that handles the localization changing, but can’t figure out how to return the viewer to the previous controller.
Perhaps this is easier accomplished with jquery?
This is the DIV from the _Layout file with the language changing buttons. It calls the action in the current controller, which means I have to define it in each of the site’s controllers. (The good thing is the view that is returned is always correct.)
<div id="top>
@using (Html.BeginForm())
{
<button id="sv_flag" name="localization" title="@Resources.Global.Sv_Flag_Hover" value="sv-SE" />
<button id="en_flag" name="localization" title="@Resources.Global.En_Flag_Hover" value="en-GB" />
}
</div>
I also tried using a specific controller for this, but cannot think of how I could return to the current view afterwards? Like so:
@using (Html.BeginForm("LocalizationAction", "LocalizationController"))
...
Edit
Now using the suggestion from Darin, I send in the controller and action values from the layout page:
@using (Html.BeginForm("SetLocalization", "Localization",
new { returnController = @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue,
returnAction = @ViewContext.Controller.ValueProvider.GetValue("action").RawValue }))
...
But I cannot get the localization changes to work, my controller action looks like this:
public ActionResult SetLocalization(string localization, string returnController, string returnAction)
{
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(localization);
return RedirectToAction(returnAction, returnController);
}
I found a completely different (and much easier and elegant) solution to my problem.
I simply created a
BaseController, that holds the action for changing the localization.Then all controllers I add to the site inherit from this
BaseController. This gives a single location for the code and does not require sending any return parameters, etc.BaseController:Each of the site’s
Controllersthen only need to inherit from it, and then mind their own actions: