15

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();
}
0

2 Answers 2

20

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");
} 
Sign up to request clarification or add additional context in comments.

2 Comments

2nd one will not work, for that return type of action should be ActionResult
Thats what I figured, hence the disclaimer. I have edited my answer
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.