I have two controllers. One is login.js and the another one is home.js. I want to redirect to home controller from login controller with a value. To redirect to home controller, i wrote,
response.redirect('/home');
But, i cannot pass value here. When rendering a view with a value,
data = {'value':'hello'};
response.render('view_login',data);
I want to do the same thing. I can pass value while rendering to the view but not when changing controller. Can i do this?
response.redirect('/home',{data: data});
you can use query parameters for this.
When you are redirecting your home page or any other controller then you can write like this
res.redirect(/<some controller>?data=<some data>)
and in that controller where you want to use this value..you can write like this
function login(req,res){
var data = req.query.data;
}
Related
The MVC project that I am currently working on uses Regions so that we can localise pages etc.
I have spotted a problem with our Error page. We have turned the custom error pages on in the web.config file. If we are on a page lets say : /IT/News/Index and we get an error, when it redirects it will go to /Error and there will be no routevalue attached to it.
Is there away to ensure that the langauge routevalue is retained by the Error page?
I have searched around and cannot find a solution at the moment and was wondering if anyone else could help or point me in the right direction?
Hope that this all makes sense. Any help is much appreciated.
If you're getting physically redirected to /Error then it's not because of the MVC HandleErrorAttribute. It's probably due to your Web.Config having system.web/customErrors defined for error handling. Using the HandleErrorAttribute causes it to inject a specific view instead of the view you would have normally returned but does not redirect you to a different action by default. The problem is when redirected because of customErrors, there is no inherant information available to tell you where they came from. But using HandleErrorAttribute DOES cause some info to be populated for you. Specifically it creates a HandleErrorInfo to use as a view model and passes that to the view you specify. For example, here's one that is reigstered in the /App_Start/FilterConfig.cs file.
public class FilterConfig
{
public static void RegisterFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute {View = "Error"});
}
}
When you redirect to an error View using the HandleErrorAttribute, certain information is populated for you. The HandleErrorInfo view model will contain the ControllerName of the original controller requested, and the ActionName of the original action. Also, the ViewData and the TempData from the original request will be copied into the ViewData and Temp data for the request to the Error view. With that information it should have what you need. Be aware that not all errors happen inside of an Action however, and exceptions that don't happen in an action will not be caught by the HandleErrorAttribute. So you'll still need to use something like customErrors (or system.webServer/httpErrors if you're doing it inside of IIS7+) to handle exceptions that occur elsewhere in your app.
Here's a link to the HandleErrorAttribute file on CodePlex in case you're wondering what it does. HandleErrorAttribute.cs
I'm not sure if this solution meets you requirements. You can override in your base controller OnException and then redirect to a specific page.
protected override void OnException(ExceptionContext filterContext)
{
string controller = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
//get other stuff from routing
//here you can do redirect or other stuff
//if handled exception
//filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
It depends how you're getting to the error pages, really. If you're using an ActionFilter-based method to catch exceptions, then you can get route values from the context that gets passed into the OnException method. If you're using a redirect from a catch block, then you can push the relevant information into TempData or pass it directly as a parameter, depending on how you're doing that redirect.
You can add a custom HandleErrorAttribute or use a base controller to be inherited by all your controllers. Either way, you need to get the RouteData object, like this
var routeData = filterContext.RouteData;
with that object, you can get all the route values accordingly to your needs. Check the object definition in MSDN site for more detail
Say you have the following route
routes.MapRoute(
"Language", // Route name
"{language}/{controller}/{action}/{id}", // URL with parameters
new { language = "en", controller = "Sites", action = "Index", id = UrlParameter.Optional } // Parameter default
Then routeData.Values.Keys will tell you the name of the parameter and routeData.Values.Values the value itself
Then, wherever you handle the exception, you can store the route data in a TempData variable, like this
TempData["RouteData"]
And after that, it will be available on your error page
#model System.Web.Mvc.HandleErrorInfo
#{
ViewBag.Title = "Error";
}
<h2>
Sorry, an error occurred while processing your request.
</h2>
#TempData["RouteData"];
I am trying to have the render name in my jade
I could do:
app.render('email', { render: 'email' }, function(err, html){
// ...
});
but I'd like to know if there is a solution to get it automaticly
Thanks
I have found it helpful to write a wrapper function around render that takes a response object, a view name, and any additional options. I then use this function exclusively instead of res.render. My implementation does things like automatically decorating the title, assigning a unique view id to all views, etc. I use it like:
render(res, 'user.new', {title: 'sign up'});
In this example, the function takes the view name 'user.new' and gives it a unique id: 'user_new_view' assigned to the body element. In your case you could simply pass the value to your template.
The benefit of this pattern is that a single function acts as an interface to all of your views (assuming you use it consistently), so if you need to change the information passed to your views you don't have to edit every endpoint in your application.
I have my controllers with the following extensions:
Controller_Login extends Controller_Layout
Controller_Layout extends Controller_Template
so that all controllers (processing user urls) will pass through Controller_Layout. In my controller_Layout, I'm trying to retrieve the controller and action url values in order to bind them and display them in my layout view.
Calling this echo $this->request->param('controller'); returns nothing (empty string), while calling echo $this->request->param(); return an empty array. Clearly nothing is found in the request.
I'm wondering if this is because I'm trying to retrieve the request values from the parent controller of where the request is actually handled. Idealy i'd like to handle this through my parent controller (controller_Layout) since every page request will need to make this call to retrieve the controller and action value
Any ideas?
To get the current Requests controller name, use $this->request->controller() instead of $this->request->param('controller'). Same goes for current action, they aren't variable parameters so they're accessed this way.
And yes, you can handle those in the parent controller, keep it DRY :)
I have a template based project in Kohana. A search form is rendered as a part of common sections of template. The searching mechanism is handled by controller called calendar. I want to call controller calendar in user controller, which I could achieve by
$this->request->redirect('calendar');
But, in calendar, $_POST is empty. How can I access $_POST which was set by submitting the search form in user controller?
Request::redirect() terminates the execution and responds with a 302 Location redirect header. Of course, you can't access the previous POST on the new page.
HMVC subrequesting can be used for cases like this:
$response = Request::factory('calendar')
->method(Request::POST)
->post($this->request->post())
->execute();
Probably the best solution to your problem, if you are unable to use HMVC subrequesting, is to store the $_POST variables you need into the session:
$my_var1 = $this->request->post('my_var1');
$my_var2 = $this->request->post('my_var2');
$session = Session::instance();
$session->set('my_var1', $my_var1);
$session->set('my_var2', $my_var2);
$this->request->redirect('calendar');
Then, in your calendar controller/action you can access said variables from the session:
$session = Session::instance();
$my_var1 = $session->get('my_var1');
$my_var2 = $session->get('my_var2');
I am using Yii. I want to have a dynamic link on a layout. This dynamic link will be modified by controllers. Let's say that dynamic link uses a user's id given by controllers to perform a task.
I am thinking to use jQuery script to get user id returned by controllers then use the user id to modify a div that holds the dynamic link.
What do you think about this technique?
It seems like you want to dynamically change a link AFTER the page is rendered, with client-side JavaScript. But it makes more sense to dynamically render a different link the first time, during the server-size PHP rendering process. The controller generates the view, after all! I would get the user ID from the controller during the page request, pass the ID in to the view, and then build the link in the view dynamically on the initial page load.
If you are modifying a link in a layout (not a view), then the best thing to do is create a variable in the Controller, and set that variable with the view. Look at how Yii uses the $layout, $menu and $breadcrumbs variables to do this.
Assuming that the user is logged in and you want their ID, you can get the ID from the Yii::app() object as well, like so:
<?php echo CHtml::link('Edit user',array('user/edit','userId'=>Yii::app()->user->id)); ?>
But at that point, you can just request the user's ID in the controller, and don't need to build a link like this.
Assuming that you want a different user ID than the logged in user, pass that ID ($userId) from the controller into the view, and just do this (as Moyersy said):
<?php echo CHtml::link('Edit user',array('user/edit','userId'=>$userId)); ?>
This will build the following link (where $userId = 99999999):
Edit user
So when the linked is clicked, in the actionEdit() you now have access to the user's ID via the GET variable $_GET['userId'].
NOW, if what you want to do is change an already created link, then you would need to use jQuery. But you will need to explain in more detail why you are doing this and what is triggering the link change (a dropdown menu?).
I'm sorry, I can't understand what you are trying to do. Specifically I don't understand what a dynamic link is.
Edit:
<? echo CHtml::link('Edit user',array('user/edit','userId'=>$userId)); ?>