Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return different views same controller in ASP.NET MVC

Tags:

c#

asp.net-mvc

I want to send the user to one of two different pages depending on the value of isCustomerEligible. When the value of that variable is set to false, it does call Index but then returns the view for Customer and not the view for Index.

public ViewResult Index()
{
    return View();
}

public ViewResult Customer()
{
    DetermineCustomerCode();
    DetermineIfCustomerIsEligible();
    return isCustomerEligible ? View() : Index();
}
like image 272
Jonathan Kittell Avatar asked Apr 15 '15 13:04

Jonathan Kittell


2 Answers

If you just return View() it will look for a view with the same name as your action. If you want to specify the view you return you have to put the name of the view as a parameter.

public ViewResult Customer()
{
    DetermineCustomerCode();
    DetermineIfCustomerIsEligible();
    return isCustomerEligible ? View() : View("Index");
} 

If you want to actually make the Index event fire and not just return its view you have to return a RedirectToAction() and also change the return type to ActionResult

public ActionResult Customer()
{
    DetermineCustomerCode();
    DetermineIfCustomerIsEligible();
    return isCustomerEligible ? View() : RedirectToAction("Index");
} 
like image 86
maccettura Avatar answered Oct 03 '22 05:10

maccettura


All you need to do is to return the View that you require.

If you want to return a View that has the same name as the action you are in you just use return View();

If you wish to return a View different from the action method you are in then you specify the name of the view like this return View("Index");

 public ViewResult Index()
    {
       return View();
    }

    public ViewResult Customer()
    {
        DetermineCustomerCode();
        DetermineIfCustomerIsEligible();
        return isCustomerEligible ? View() : View("Index");
    }
like image 38
Harko Avatar answered Oct 03 '22 04:10

Harko