Question

I have created a controller called loginController.cs and i have created a view called login.aspx

How do I call that view from loginController.cs?

The ActionResult is always set to index and for neatness, I want to specify what view the controller uses when called rather than it always calling its default index?

Hope that makes sense.

Was it helpful?

Solution

You can customize pretty much everything in MVC routing - there is no particular restriction on how routes look like (only ordering is important), you can name actions differently from method names (via ActionName attribute), your can name views whatever you want (i.e. by returning particular view by name).

return View("login");

OTHER TIPS

In the interest of actually answering the question.. you can add a route ABOVE your default route in Global.asax:

routes.MapRoute(
    "SpecialLoginRoute",
    "login/",
    new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

..although, without properly thinking through what you're trying to achieve (that being.. changing what MVC does by default) you're bound to end up with lots and lots of messy routes.

Your return the view from your controller via your Action methods.

public class LoginController:Controller
{
  public ActionResult Index()
  {
    return View();
    //this method will return `~/Views/Login/Index.csthml/aspx` file
  }
  public ActionResult RecoverPassword()
  {
    return View();
    //this method will return `~/Views/Login/RecoverPassword.csthml/aspx` file
  }
}

If you need to return a different view (other than the action method name, you can explicitly mention it

  public ActionResult FakeLogin()
  {
    return View("Login");
    //this method will return `~/Views/Login/Login.csthml/aspx` file
  }

If you want to return a view which exist in another controller folder, in ~/Views, you can use the full path

   public ActionResult FakeLogin2()
  {
    return View("~/Views/Account/Signin");
    //this method will return `~/Views/Account/Signin.csthml/aspx` file
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top