Custom controller for the layout.cshtml - c#

I have an MVC website which I wanted to implement a globalization/localization. On my _Layout.cshtml, I have a dropdown which have the languages I supported. When a user selected a language on that dropdown, it should automatically post to the server then render the new language.
Is it possible that I create a specific custom controller for the _Layout.cshtml only? If yes, how? If no, is there any possible way or approach I can make?
Thanks in advance!

You should move that to a child action, then call the child action from the layout view.
You can make the form POST to a separate action (in a controller shared with the child action) that sets the cookie / session / DB property, then redirects back to the original URL (via Request.UrlReferrer or from a hidden model-bound field).

Related

ASP.NET Core 6 How to redirect from one view to other

tl:dr:
I would love to redirect from my Layout view into an index view of a certain class. I do not want to do it through a button.
After I log in the layout page changes depending on your role. If you have a regular user role I want you to be immediately redirected to another view.
This the part of the code where I would like the redirecting to take place. In the "else" clause.
Is there a simple way about please?
I was thinkig of calling a method from a controller of said class which would simply have the redirect method inside. But that has failed since I was not able to call such method simply in a view and I failed to find a way after a long google search.
Thank you for your help.
According to your description, if you want to redirect the view from layout to another view, I suggest you could consider using the Context.Response.Redirect("~/Account/LogIn");
More details ,you could refer to below example:
#if (Context.User.Identity.IsAuthenticated)
{
}else
{
Context.Response.Redirect("/home/Privacy");
}

Calling a specific action of a controller on the click of HTML button(Not Submit or Form's post Button) Asp.net MVC

When we click a Form's submit button, then action of the controller which is having HTTPPost attribute is called but what if i want to call or perform an action when a normal HTML button is clicked
Although following articles
http://www.codeproject.com/Tips/198477/Calling-a-MVC-Controller-and-Action-Method-using-H
HTML button calling an MVC Controller and Action method
tells the approach but both of these are using controller name in view, So view has to know about controller, I am looking for an answer that view wont have to know about controller.
because views has to be Independent from Controller, Views should not know about controller
So, if you know the answer then please reply
any form that directs your user to url created by
<a href='#Url.Action("{action}", "{controller}")'> click me </a>
or
#using(BeginForm("{action}", "{controller}")
will do what you want.
That can be with a
form
button link
It's the destination that matters. The View does not "know" anything about the action or controller. The helper does.
To execute an MVC action from the client side (i.e. from a view) you need to hit a URL (with any verb: get, post, put, etc).
Therefore to execute an action form a view you will need to know the URL of that action, by default that URL is directly mapped to the controllername/actionname but you can re-define this if you want to create more abstraction between view and controller.
Given this your button just needs to be a link to a URL or linked to js to do an Ajax http request.
Hope that helps.
You cannot have 2 actions on the same controller with the same name and the same HTTP verb. So what you are asking doesn't make sense. You could invoke the same controller action as the one that rendered the view without specifying an action and controller name. The reason why Html.BeginForm() works without specifying an action and controller name is because the form is sending a POST request to the server and you can distinguish the 2 actions.

How to implement logic at "masterpage" level

I'm still new to MVC, so bear with me :-)
I've got a community site I'm working on, and I'd like to show how many users are online on all my pages after the user's been logged in.
I've got a shared view which is used as layout for all pages after login (UserLayout.cshtml)
Can I somehow add the logic to show online count to my shared layout ?
If it were WebForms I'd just have some code-behind for my masterpage, but this is obviously not an option here.
The information about users online is fetched from a cache. It's not available as a property on any of my View Models.
You can write an action which renders the information (using a very small view)
You can then call Html.Action to render it from the layout page.
You can create a 'UserLayoutModel' class and have all other view models derive from it. You can also use 'RenderAction' to have a part of the UI rendered separately (make sure you mark this action with ChildActionOnly attribute).
What I did was create a BaseController.cs that all controllers inherit from, and in the base controller you can override OnActionExecuting and any viewdata values you set here will be available to your master page.
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
base.OnActionExecuting(filterContext);
}
You can create a Global Action Filter.
Normally you add an Action Filter as an attribute to a method or class ([HttpPost]). Using a global Action Filter you can add code to every Action, without the need to inherit from a specific class. It is like you added an attribute to each and every Action method.
This article explains a lot.

C# Handle GUI in MVC

I am using the asp.net MVC Framework. IN my application a user has to log in. And when the combination of username and password is correct, the div (or panel?) with with the menu in it, must become visible. But how can I do this? When a name my panel pnlMenu, in my controller i cannot do something like:
pnlMenu.visible = true;
So, how do i have to do this?
What you should do is in your controller check to see if a user is logged in and set a value in the ViewData like this:
ViewData["IsLoggedIn"] = true;
Then in your view you can set the visibility of the method based on this value. This way if you change the view later, or decide to have multiple views, they can each use this value and there isn't any coupling between your view and your controller.
Create a method or property on your View that enables you to hide or show the appropriate controls ?
Then, in your Controller you can access that property or method of your View, can't you ?
You do not want to reference specific 'controls' on your View in your controller, since, one of the ideas of MVC is that you can just replace the UI with another implementation (web / win / ...) and make use of the same controllers and application logic.
Then, you just want to describe an operation that your View should support, so, in the interface that describes the 'contract' that your View must support, you should create a method which is called 'ChangeState( bool loggedIn )' for instance.
In the controller, you can call this method when the user has logged in.

Put current route values/url in form post

In my master page, I have a language dropdown menu. When the user selects a language from the dropdown, a submit sends the currently selected language to the "Translate" method in my controller. After which it should redirect to the url it was before the translation submit so it can show the exact same page, but now in the newly selected language.
How would I best go about this? Should I send the current url somehow in a hidden field? Or can I maybe send the current routevaluedictionary, so my translate method can redirectToRoute directly?
Or maybe there is an entirely better way?
--EDIT--
Because I want my bookmarks to include the site language too, all my exposed actions have a siteLanguage parameter too. If I could somehow efficiently show the user a bunch of regular (GET) links where the siteLanguage parameter is filled in with the relevant value, that would be even better. But as far as I know, there is no way to put links in a dropdown except with java maybe.
I have a similar situation, and I solved it slightly differently.
Because my master page had functionality in it, I created a new base controller class (that inherits from Controller) and all my real controllers inherit from my custom class.
Then, I implement OnActionExecuting in the base class to do some common work.
Then, in your masterpage, if you have a form like this, it will submit to the current URL with a GET request and add the language as a querystring parameter:
<form id="language" method="get" >
<select name="language">
<option value="en">English</option>
<option value="es">Spanish</option>
...
</select>
</form>
Use jQuery to wire it up to autosubmit, etc.
You could look for a language parameter in the querystring in your base controller class and set the flag that tells the real controller method which language to use. In the model, you directly go to the real controller to regenerate the page and avoid a redirect.
Note, this only works universally, if you are not already using querystring parameters.
If this doesn't work for you, you could also use your current method, but include the URL to be redirected to in a hidden field like this:
<%= Html.Hidden("redirect", Request.Url %>
public ActionResult Translate(string _lang){
switch(_lang){
case "English":
return View("English");
case: "French":
return View("French");
default:
return View("English");
}
I would personally do it like this
I would put the return url in the querystring, just like forms authentication does when it redirects to the login page.
Include the returnUrl in the routeValues when you do your Translate request.

Categories

Resources