简体   繁体   中英

Could an action can have more than one view in a controller?

I want to use an action which takes an id as a parameter and do a check whether id is null or not. If id is null, I need to pass a list of model(for example person model), if is not, I need to pass a single model. I need to use 2 view for my action, one of them take model as IEnumerable and other one just take a single model. I have solved this problem with using 2 actions, but I wonder whether there is a more easier way or not? Thank you.

Yes, you just need to specify the name of the view, for example:

public ActionResult SomeAction(int? id)
{
    if(id.HasValue}
    {
        var item = GetSingleItem(id);
        return View("SingleModelView", item);
    }   
    else
    {
        var listOfItems = GetAllItems();
        return View("EnumerableModelView", listOfItems)
    }
}

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