ASP.net MVC default route to show actual route - asp.net-mvc

I have an MVC 3 app, my default route is app/index, which mean that if a user hits "http://www.something.com",
they are acutally seeing "http://www.something.com/app/".
However, I want to show the actual route always, which mean that when a user hits
"http://www.something.com", I want the url in address bar to be shown as "http://www.something.com/app/". How can I achieve this?

You can use an redirect in your action as follows:
public class HomeController : Controller
{
public ActionResult Index(){
return RedirectToAction("Index","App");
// or you can do a redirect to a URL. like 301.
return RedirectPermanent("/app");
}
}

Related

ASP.NET MVC - Redirect(); is not redirecting correctly

I have something like this:
public class AccountController : Controller
{
public ActionResult Login()
{
return Redirect("http://localhost/");
}
}
I would want it to redirect user to that page, but it keeps redirecting it to
http://localhost/Account/http://localhost/
What am i doing wrong here?
Redirect to application root :
Redirect("~/");
I assume that you're trying to redirect it to the home page given that code. In which case, you should probably just use RedirectToAction, as follows:
return RedirectToAction("Index", "Home");
Ok, i solved my problem. In reality i was passing encoded url into my Redirect(); method. It seems that this method can only work on unencoded versions of links.

register and login in one page changes my url

Im having the following issue.
I have a View typed to a class SiteAuthenticationVM.cs.
The name of my view is "SiteAuthentication.cshtml" into the folder Views/Users
For other hand, i have one controller called UsersController with 4 actions:
[HttpGet]
public ActionResult Registration()
{
return View("SiteAuthentication");
}
[HttpPost]
public ActionResult Registration(SiteAuthenticationVM usertoregister)
{
return View("SiteAuthentication",usertoregister);
}
[HttpGet]
public ActionResult Login()
{
return View("SiteAuthentication");
}
[HttpPost]
public ActionResult Login(SiteAuthenticationVM usertologin)
{
return View("SiteAuthentication",usertoregister);
}
I have 2 routes defined:
"/register" is handled by UsersController Registration action.
"/login" is handled by UsersController Login action.
When i post my Login form is posted to /login if previously i was in url "/register", it changes to /login. Is there any way to keep my url "/register" for both post actions?
Is a bad practice if the url changes?
Your URL is denoting the controller method which is called, not whih View is being displayed. You can't change that, this is how MVC works. And your browser doesn't like to change its URL to 'B' if it needed 'A' to display that page, you cant really change it at rendertime.
Funny thing, if you had given your methods the same name, and had named your views differently, it would've worked without a hitch :-)
However, there are a few ways I can think of to get around this:
Give your methods the same name. This is the most straight-forward option. You can keep your View names, it's the method name that is important.
Make a method (e.g. "Switchboard") that calls either return View("Login") or return View("Register"). Your URL will contain "Switchboard" (you'll want a better name, but you get the idea).
Make the Login and Register pages into PartialViews. Display these in 1 View ("Switchboard", same name method). Then the URL will always denote the method ("Switchboard") you called for the View, not the PartialView.
Just remember, in MVC it's not about which View you are displaying, it's about which method you are calling.

How can I make an MVC POST return me to the previous page?

I have the following action which is called from a screen with a list of records.
[HttpPost]
//[Authorize(Roles = "admin")]
public ActionResult Edit(EditViewModel itemView)
{
Once the action has completed I would like to return to the page where the action was called from. However I don't want to refresh that page. I just want to go back to the populated screen using something similar to the "Previous" button in the browser. Right now when I click "save" my action does the following which is not what I want:
return RedirectToAction("Index");
Is there some way to Redirect to previous page with MVC3?
Something like the Stackoverflow functionality after I click edit to edit an answer where it returns to the post.
Instead of a redirection,
[HttpGet]
public ActionResult Index()
{
/// preform any processing necessary for your index page on GET
return View("Index");
}
[HttpPost]
public ActionResuit Edit(EditViewModel itemView)
{
if (ModelState.IsValid)
{
/// do whatever you want with your model...
}
// return the contents as they'd be rendered by the Index action
return Index();
}
Note that with this method the URL in the browser will still display the Edit url (like /area_name/edit), but you can fix that by:
Using a redirect (which you've said you don't want to do)
Using JavaScript to update the URL, or use history.back() as #AlanStephens suggested
Probably other methods that don't immediately come to mind.
However, I'd question whether this is really the best approach. Typically, users expect different URLs to do different things.
Or, if I understand you correctly and the edit action is being called from the Index page,
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost] /// from a form on Index
public ActionResult Index(EditViewModel model)
{
if (ModelState.IsValid)
{
////
}
return View();
}
and just take the /Edit out of play entirely. Again, I don't really care for this approach.
Based off the code you've given, it looks like you've got a paginated screen, with the ability to click edit on each row. Here's how I've solved this problem in the past.
On the Index page, when the page loads, whether it be from the main index or a paging method, add the following:
Session["CurrentUrl"] = Request.Url.ToString();
So now, at the end of the POST method for your edit page, do:
return Session["CurrentUrl"] == null ?
Index() :
Redirect(Session["CurrentUrl"]);
What you described is easily achieved using ajax calls. That way you perform whatever action you like and afterwards (on successful response), you can easily navigate from the current page, using javascript.
If you POST to a page and in response you return the same view you receive with a GET request (index page), then some users might hit F5 to reload that index page and get a warning in the browser, which actually says it will send the POST request again. This is pretty confusing for users and not really user friendly (not to mention numerous concerns related to idem-potency of it).
Although you don't like the redirect approach, because of the additional response, I guess, I should say that, in MVC, this is the correct way to do it, assuming you don't want to use ajax calls.

RedirectToAction problem

I have a Controller: AdminPageController, in which I have the following actions: Index, Create, Save
My save action is as follows:
public ActionResult Save(string[] inputs, int columnsCount)
{
.....
return RedirectToAction("Index");
}
I can see that the debugger passes throug the redurectToAction , but the index is not displayed. I can see that the routing is written as follows:
http://localhost:55405/AdminPage/Create#
What is wrong and how can I solve it?
Please use this utility displays the route data pulled from the request of the current request in the address bar. So you can type in various URLs in the address bar to see which route matches.
http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

Can MVC routing be used to create a dynamic content management system with dynamic pages stored in db rather than in view pages

Are there any good examples of mvc routing wherein every 404 page not found request is routed to a standard view in MVC which basically pulls the content from the database.
Just add this route to the bottom of your RouteTable:
routes.MapRoute("DynamicPages", "{*page}", new { Controller = "DynamicPages", Action = "Show", Page = String.Empty });
And create a controller for displaying dynamic pages from db:
public class DynamicPagesController : Controller
{
public ActionResult Show(string page)
{
var pageContent = DB.GetContentForPage(page);
return Content(pageContent);
}
}
Here's one way to do this: In your global.asax file in Application_Start, you need to set the default controller factory. Override it with an instance of your own factory.
void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
}
MyControllerFactory should inherit from DefaultControllerFactory and when selecting the controller to use, look in your database for the appropriate page you want to display. If the page exists, select the appropriate controller and override the action in the requestContext.RouteData collection to point at the appropriate action for displaying dynamic pages.
If the requested page doesn't exist, pass back a call to the base method and let it do what it would normally do.
There are other ways you could do it, but this one should work and allows you to intercept the request before you hit the 404 page.
modify the web.config file, you may Reference to this page and look at the setting custom error pages in web.config section.

Resources