3

I want to pass more than one object in the view. I have two object. One name is "Caller" and one Name is "Receiver". I am new in MVC. This is my action method.

public ActionResult IsActiveCaller(int id)
{
      var caller =  new CallerService().getCallerById(id);
      if(caller.active)
      {
             var reciver= new reciverService().getReviverTime(caller.dialNo);
             return (caller ) // here i also want to send reciver to view
      }

      return View();

}

Is there any way to send more than object in view?

3 Answers3

3

Yes you can do this. There are multiple ways to do this.

1) You can use viewBag to pass the data or object into view.

You can see here to see how to use viewBag in mvc

2) you can use ViewData but it is not a good approach.

3) you can make ViewModel like as below (recomended)

public class callerReciver
{
    public Caller caller {set;get;}
    pblic Reciver eciver {set;get;}
}

Now pass callerReciver to view.You can access both object.hope you will understand.

4) Another way is to use partial view.You can make partial view to use more than one object in same view.

Community
  • 1
  • 1
Umer Waheed
  • 4,044
  • 7
  • 41
  • 62
1

You can use a View Model:

public class MyViewModel
{
   public Caller Caller { get; set; }
   public Receiver Receiver { get; set; }
}

Then you can populate the view model this way:

public ActionResult IsActiveCaller(int id)
{
      var caller = new CallerService().getCallerById(id);    
      var vm = new MyViewModel {
           Caller = caller
      };
      vm.Receiver = caller.active ? new reciverService().getReviverTime(caller.dialNo) : null;
      return View(vm);
}

View:

@model MyViewModel
<h1>@Model.Caller.Title</h1>
@if(Model.Receiver != null) {
   <h1>@Model.Receiver.Title</h1>
}
Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110
0

The cleanest way is to pass by a view model :

  • ViewModel
public class MyViewModel {
    public Caller MyCaller { get;set; }
    public Receiver MyReceiver { get;set; }
}
  • Controller
public ActionResult IsActiveCaller(int id)
{
      var caller =  new CallerService().getCallerById(id);

      var viewModel = new MyViewModel();
      viewModel.MyCaller = caller;

      if(caller.active)
      {
             var reciver= new reciverService().getReviverTime(caller.dialNo);
             viewModel.MyReceiver = reciver;
      }

      return View(viewModel);
}
  • View
@model MyViewModel

<h1>@Model.MyCaller.Id</h1>
<h1>@Model.MyReceiver.Id</h1>
Guillaume
  • 844
  • 7
  • 25