简体   繁体   中英

Return different views same controller in 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();
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM