1

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.

1 Answers1

2

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)
    }
}
Shaiju T
  • 6,201
  • 20
  • 104
  • 196
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • your if statement looks like it should be flipped – Fran Jul 10 '18 at 17:17
  • @Fran , I guess you mean `GetSingleItem` should use `SingleModelView` and `GetAllItems` should use `EnumerableModelView` , I have updated. – Shaiju T Jul 11 '18 at 06:16
  • Thank you for solution, but I have faced with a problem. I passed models successfully, but when I tried to print the datas which are in a related table, I got NullReferenceException. The problem is that I have necessary datas in my database. Have you ever faced with this kind of a problem? – Yusuf YENİÇERİ Jul 12 '18 at 22:39