Unexpected controller and action values - ruby

I am viewing my parameters when testing my ruby on rails application, and the controller and action values are not what I would expect based on the routes.rb file or when running "rake routes".
For example, the URL http://localhost:3000/crimpers/1
yields the parameters of:
{ controller: ecrimp, action: show, id: 1}
whereas I would expect it to be:
{ controller: crimpers, action: show, id:1 }
However, for http://localhost:3000/crimpers, the parameters are the expected:
{ controller: crimpers, action: index }
crimpers_controller.rb contains the actions index, create, update, edit, show, new and destroy.
ecrimp_controller.rb contains the actions welcome and ecrimp.
routes.rb:
root 'ecrimp#welcome'
get 'ecrimp' => 'ecrimp#ecrimp'
resources :crimpers
resources :hose_specs
resources :hose_specs do
collection { post :import }
Why might the controller and action be defined in such a way for the first url?

Related

How to redirect to view from shared folder

HttpContext.Response.Redirect("~/Shared/views/Error.cshtml", true);
This is not working for me
And how to exclude the certain controllers and actions
As you can see in documentation, method which you are trying to use require to arguments
public void Redirect(string url, bool endResponse)
and first argument is an url of page where user should be redirected, while you are passing view file path. In asp. mvc path to *cshtml file is not equal to url.
I suggest you to use RedirectToRoute method instead
RedirectToRoute(new RouteValueDictionary
{
controller = "Error",
action = "Index"
})
where your desired view is returned by ErrorController.Index() action.

View from custom controller overriding default view

I'm using orchardcms 1.9 (no tag created jet). I am writing a custom module that implements its own controller that calles a service wich check some information and based on the service response I either redirect or let the user stay on the page.
The module is on the default layer in other words it is on everypage. So when user tries to log in or register this module checks information normally.
This is my route:
new RouteDescriptor {
Priority = -1,
Route = new Route(
"{*path}", // this is the name of the page url
new RouteValueDictionary {
{"area", "modulename"}, // this is the name of your module
{"controller", "controllername"},
{"action", "Redirect"}
},
new RouteValueDictionary(),
new RouteValueDictionary {
{"area", "modulename"} // this is the name of your module
},
new MvcRouteHandler())
and this is my controller:
public ActionResult Redirect()
{
String response = _authService.VerifyRegistration(_orchardServices.WorkContext.CurrentUser);
if (response.Equals("2"))
{
Response.Redirect("~/Registration");
}
else if (response.Equals("3"))
{
Response.Redirect("~/Users/Account/LogOn");
}
return View();
}
What happens is that when I go to registration or login controller triggers, checks the infromation, says no redirect needed then returns view. But because the view is empty my page is blank instead of its default login/registration form.
How can I solve this? Am I making a mistake in routing that I somehow override the default view (I tried different priorities but same response).
Your route overrides all routes ({*path}. So when you redirect, you redirect to....your redirector I guess. Therefore the view you are rendering is the one for your controller, not the page you were after.
Whatever the logic flaw - this is not a good way to globally control authorization type scenarios on your site. If you meant to have a single page that people might go to (e.g. http://www.mysite/welcome) then your problem is that your route is too global. However, if, as your code suggests that you want to create a "all pages" check to see if you should go to login or register, then you should implement an authorization filter. An example of an authorization filter (for a slightly different purpose) can be found at https://stackoverflow.com/a/30377097/1638254 . You are looking to fill in the OnAuthorization method with suitable code to redirect the user (or let them through

MVC3 Why do I get "Child actions are not allowed to perform redirect actions" error?

I got an action List
//[HttpGet] (will come back to that!)
public ViewResult List(int page = 1)
{
//blah blah blah
return View(viewModel);
}
In its view we render action:
#{
Html.RenderAction("UpdateSearch");
}
Action definitions:
[ChildActionOnly]
[HttpGet]
public PartialViewResult UpdateSearch()
{
// do something and display a form in view
return PartialView(so);
}
[HttpPost]
public RedirectToRouteResult UpdateSearch(Options searchOptions)
{
// do something and redirect to List
return RedirectToAction("List");
}
and I'm getting: Child actions are not allowed to perform redirect actions exception every time someone submits the form. I'm new to MVC3, but it looks like the redirection is also a POST, because if [HttpGet] above List method is uncommented "the resource cannot be found" happens.
How do I change Http method on redirection or am I doing something wrong? I did try to Bing it, but no success.
The redirect info is stored in response header. However, the response is already being sent when child action is run so headers can't be written.
In short, there's no way of performing a redirect from child action other than through the use of javascript on client side.

C# MVC RedirectToAction not working?

So I want to create a new view in my MVC application that allows a user to enter parameters for searching. I want to pass these parameters to another View/Controller and I want the controller to call an action called "Search" to handle these parameters and return the correct data. However, when I try to "Redirect" it is giving me a problem. It says the resource cannot be found,
The view 'Search' or its master was not found or no view engine supports the searched locations.
The following locations were searched:
~/Views/Question/Search.aspx
This is the code.
[HttpPost]
public ActionResult HandleForm()
{
SearchQuery search = new SearchQuery();
if(Request["QuestionID"].Trim()!="")
search.QuestionID = Convert.ToInt32(Request["QuestionID"].Trim());
return RedirectToAction("Search", "Question");
}
However, if I change "Search" to "Index" it loads the page I desire because it opens the view within that page. It does not call the search action. Why is this method returning the View when every example I've read states that the name of the Action needs to be passed?
For those who are wondering this is my global.asax routing info
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Last but not least, I have yet to look into how to pass these parameters, but I hope it won't be too much extra work once I can figure out why this is not working as desired.
Go to the Views/Questions directory and make sure there is a file called Search.cshtml. If it does exist also then make sure that this view has a corresponding action method, something like:
public class QuestionController : Controller
{
public ActionResult Search()
{
}
}
If you are in same controller then write:
return RedirectToAction("Search");
or if your search action is in other controller then write:
return RedirectToAction("Search","your Controller Name Here");

Grails UrlMappings for a telephone number

I'd like to set it so when a user visits the application with a telephone number in the URL Grails directs the user to the specified profile, for example:
localhost:8080/Application/profile/07871216969 -> /user/show/User.findByUserTelephone(07871216969)
or preferably
localhost:8080/Application/07871216969 -> /user/show/User.findByUserTelephone(07871216969)
However, I have no idea how to reference the telephone number in the URL when calling the findByUserTelephone closure; I've noticed something like:
/profile/$telephoneNumber however I'm not entirely sure how that works out.
Also, as the /user/show action requires an id in the parameters I am not sure if the findUserByTelephone closure is any use as it returns the User as an object, and I can't seem to either getId() or .id the object to retrieve the id.
SOLVED/SOLUTION:
I solved this by creating another action in the Controller called profile, this action then had code similar to the following:
def profile = {
if(User.findByUserTelephone(params.userTelephone)) {
def userInstance = User.findByUserTelephone(params.userTelephone)
if (!userInstance) {
flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
redirect(action: "list")
}
else {
[userInstance: userInstance]
}
} else {
render("Sorry, that user wasn't found in our database.")
}
}
I then created the following UrlMapping entry:
`"/$userTelephone"(controller: "user", action: "profile")`
Thus, when a user enters a telephone number into the system (or any string after the /) it will route the user to the user/profile action, which will attempt to find a user by their telephone number. If successful, will show the users details otherwise will show an error message.
It will probably save you some headaches later if you use a url path which is not the same as a controller name. So if you have something like:
"/p/$phoneNumber"(controller:profile, action:show)
you won't have any URL patterns that match multiple URLMapping entries which can get a little confusing. I would guess that just:
"/$phoneNumber"(controller:profile, action:show)
would work, but I would expect to end up in situations where Grails gets confused by multiple URLMappings matching the same request path unless you're very careful.

Resources