How to redirect to view from shared folder - asp.net-mvc-3

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.

Related

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

handle direct url with history api in asp.mvc

I have my site like http://mysite.com/ and on the index page i have search box and for the result i am using jqgrid. When user click row in the jqgrid row I am taking data from cells and do ajax call to server and fetch json data and once data arrived I hide the search box and jqgrid and show another div which is I kept for result. In short, user will be on the same page just div's hide/show.
Now I have seen history api and used pushState and popstate so my url becomes in the addressbar like http://mysite.com/controller/action/para1/para2 (here para1 and para2 are the parameters i am passing to action). Everything is ok so far.
Now the problem is if I copy this URL "http://mysite.com/controller/action/para1/para2" and if I open this with let's say different browser and hit enter it display just json data. So, I am confused that how to handle when user directly use that url in controller.
I was thinking to check in the controller action if the request is AJAX then return json data otherwise full page, is that right approach? OR something on the client side we have so that it load the same way as earlier.
Thanks
if I copy this URL "http://mysite.com/controller/action/para1/para2" and if I open this with let's say different browser and hit enter it display just json data.
it only display json data because its ajax call only so how to deal with that so that it also display the same page even user directly access the url.
I think what you're looking for is Request.IsAjaxRequest():
public class FooController : Controller {
public ActionResult GetFoo(int id) {
var model = _fooService.Get(id);
if (Request.IsAjaxRequest())
return PartialView("_Foo", model);
return View("Foo", model);
}
}
Note: It's recommended to use WebAPI controllers to handle only json data. So if the user got there by typing the url the mvc controller will handle it and if you need to get the json data for that view you could call the webapi controller.
Use a separate controller or action method for AJAX and for Views. The View controller should match the URL. The Ajax controller should be the less "pretty" URL since it's behind the scenes.
You need to set up a routing definition in global.asax (MVC 3) or App_Start/RouteConfig.cs (MVC 4) to handle the parameters if you haven't already done that.
routes.MapRoute(
"MyRoute",
"MyUrlController/{action}/{para1}/{para2}",
new
{
action = "Index",
para1 = UrlParameter.Optional,
para2 = UrlParameter.Optional
}
);
Then in the View controller:
public ActionResult Index(string para1 = "Default Value", string para2 = "Default Value")
{
// ...Handle parameters...
return View("_MyView", viewModel);
}
Returning a View object type is the key. The History API URL doesn't get it's data from the same AJAX source controller which returns a PartialViewResult.

MVC3 MapRoute to convert aspx query params into the route

I'm working on a project to rewrite an aspx site as MVC3. I want to make the old URLs work on the new site. I have named my controllers and actions such that the URLs actually contain enough info in the query string to route correctly but I'm having trouble getting the routing to work since it doesn't like the ? in the URL.
Basically I have old URLs like this:
www.example.com/Something/SomethingElse/MyPage.aspx?Section=DetailSection&TaskId=abcdef
I tried to create a route using:
routes.MapRoute(
"OldSite",
"Something/SomethingElse/MyPage.aspx?Section={action}Section&Id={id}",
new { controller = "Task", action = "Index", id = UrlParameter.Optional }
);
I want it to route to the correct new URL which is:
www.example.com/Task/Detail/abcdef
I know that all traffic to the MyPage.aspx page should go to my new Task controller and the beginning of the Section parameter always matches one of a few corresponding actions on that controller.
Unfortunately I have found that I get an error that a route can't contain a question marks. How should I handle this? Would it be better to use URL rewriting? Because this is a private site I'm not concerned with returning permanent redirects or anything - no search engine will have links to the site anyway. I just want to make sure that customers that have a URL in an old email will get to the right page in the new site.
In this one case I think the simplest way would be to have your old page mapped to a route:
routes.MapRoute(
"MyPage",
"Something/SomethingElse/MyPage.aspx",
new { controller = "Task", action = "MyPageHandler" }
);
And have this route mapped to an action method in TaskController:
public ActionResult MyPageHandler(string section, string taskId)
{
if (section.Contains("Detail"))
{
// execute section
}
}
This way you're treating your old site's query string for what it is: a query string. Passing those parameters straight into an action method is the most MVC-y way to interpret your old site.

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

Configure asp.net mvc hocalhost/Products.aspx to hocalhost/Products

How to configure asp.net mvc routing to redirect permanently 301
hocalhost/Products.aspx and hocalhost/Search.aspx
to
hocalhost/Products and hocalhost/Search
i.e. to remove .aspx extension from the path?
Something along these lines should do the trick. Map the following route:
routes.MapRoute("Redirect route", "{file}.aspx",
new { controller = "home", action = "redirect" });
And define a Redirect action in your controller:
public ActionResult Redirect()
{
// use Request.RawUrl, for instance to parse out what was invoked
// this regex will extract anything between a "/" and a ".aspx"
var regex = new Regex(#"(?<=/).+(?=\.aspx)", RegexOptions.Compiled);
var action = regex.Match(Request.RawUrl);
return RedirectToActionPermanent(action.Value);
}
You could redirect both aspx pages to the same redirect route and detect which file has actually been invoked by parsing HttpContext.Request.RawUrl (there might be a better way for this last point though).
UPDATE
There is indeed a simpler way, as found out by #alex himself. In order to get the file in the original request, just do:
string file = RouteData.Values["file"].ToString();

Resources