Accessing a method in a BaseController from a Layout View in MVC4 - c#

In my MVC4 web application I have both a GlobalController which all controllers will inherit from so I have a single place that has all the common code that must run on each and every page. I also have a _MasterLayout.cshtml page that all my views use as there layout page. So far I have been able to put code in my GlobalController to fill ViewBag data with stuff to propagate dynamic data to the _MasterLayout.cshtml file.
I now need to figure out how to place buttons and/or links that people can click on to do things like register, login, logout, etc. As you could imagine these functions could be used on any page in my site so I would like the code for those to live in my GlobalController. I have already created public classes inside the GlobalController to do the actions I want but what I can not figure out is how to wire up a click on either a link or button placed on the _MasterLayout.cshtml file to the GlobalController public class?
I DO NOT WANT TO RENDER NEW VIEWS!

Your BaseController should only contain methods that controllers need to know how to do, like finding Views hence the View() method. Then every other controller should take care of their own jobs. So for Login, Logout, Register those all deal with account management. So you would create an account controller and put those actions inside
public class AccountController: BaseController {
public ActionResult Logout() {
/* logout user */
}
.....
}
And then in your views you would just create an action link to to what you need.
<div id="header">
#Html.ActionLink("Log me out", "Logout", "Account");
</div>
or you can call it directly
<div id="header">
Log me out
</div>
Hope this helps get you on the right track. I would also suggest going through the Music Store Tutorial for a better idea of working with MVC.

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");
}

How do I add a button click event on a different class in .Net MVC?

I am newbie with asp.net MVC and i want something simple. I have an Index.aspx page and a UrlContent.cs class.
I am searching how to write the code of the button_click listener of the page in the class. So far havent found anything on google.
Thats all, thank you
MVC is a different paradigm, and doesn't really have the concept of "event listeners".
That concept was always an abstraction from how web clients/servers really communicated. To a web server, there's really only one event, and that is an HTTP request from the client. To achieve the illusion of "events", ASP.Net does some (Javascript+cookies) magic behind the scenes, and creates hidden form input tags -- containing info about which button was clicked -- within a standard HTML form, and posting the form back to the server.
MVC adheres much more closely to the native behavior of HTML/HTTP. It requires you to get accustomed to working with those technologies -- forms, GET/POST requests, and AJAX.
To handle a (submit form) button click event, you create an action in your controller that accepts parameters.
Controller
[HttpPost]
public ActionResult Index(MyModel model)
{
// handle the submit button's "click event" here
}
View
#model MyModel
#using (#Html.BeginForm("Index", "Home")) {
#Html.EditorForModel
<input type='submit' value='submit' />
})
If you're running MVC, I think you're looking for something like this
#Html.ActionLink("Link Text", "Action method Name", "Controller name",new {} , new {})
Here's some documentation on more overloads.

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.

ASP.NET with MVC 2 in VS2010

Hi
i want to do a work in asp.net using mvc and ajax
i have a button
when i click that button,its text should be changed.e.g before click(Click me) after click(u clicked me)
but i want to do this work in MVC2
i have studied but couldn't understood mvc
kinfly do this example so that i can understand it easily
Best Regards:
Shaahan
are u just trying to change the text label on click?
there's a few ways to do this, but you can probably just use an onclick event and change the label straight when the user click on the button.
for example like so.
but if you want to do it MVC just for the heck of it, then you can create a view, click on the button and do a form post to the same page, and on the controller use ViewData["ButtonLabel"] and update the button label when the page goes back :P
You can do what you want simply with javascript. If you want to learn mvc here a simple [music store][1] tutorial that I has helped me a lot! [1]: http://www.asp.net/mvc/tutorials/mvc-music-store-part-1
MVC stands for Model, View, Controller.
The way this works is you have a controller, say HomeController which is a class derived from Controller. When you access /Home/ on the site through your browser it serves the browser a view and any additional information, often cookies and such. The model is the data and logic of the program, often handling things like databases.
There are multiple ways to go about this example.
//In HomeController class
public ActionResult Index()
{
return View();
}
public ActionResult Clicked()
{
return View()
}
And then for the Views for the index view you'd have a button which would link to /Home/Clicked. Then on the clicked view you'd have the button with changed text.
Of course this is only one way to do it you could just append a number do the /Home/ url and pass that to the view and if it's not 0 have the test be different or use javascript to change the button's text
Index view:
<form>
<input type="button" value="NClicked" onclick="window.location.href='/Home/Clicked'">
</form>
Clicked view:
<form>
<input type="button" value="Clicked" onclick="window.location.href='/Home/'">
</form>
Of course there's more to the views than that, but you can insert that into your body.

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