如何在MVC中向视图传递多个对象?

3

我希望能够在视图中传递多个对象。我有两个对象,一个叫“Caller”,一个叫“Receiver”。我对MVC还很陌生。这是我的操作方法:

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

}

有没有办法在视图中发送多个对象?


你可以使用ViewModel。 - Sirwan Afifi
3个回答

3

是的,你可以做到这一点。有多种方法可以实现。

1) 你可以使用 viewBag 将数据或对象传递到视图中。

你可以在 这里 查看如何在 MVC 中使用 viewBag。

2) 你可以使用 ViewData,但这不是一个好的方法。

3) 推荐的方法是创建 ViewModel,如下所示:

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

现在将callerReciver传递给视图。您可以访问两个对象,希望您能理解。

4)另一种方法是使用部分视图。您可以使部分视图在同一个视图中使用多个对象。


谢谢。我明白如何传递参数,但额外的知识对我也很有帮助。再次感谢。 - user4863604
非常欢迎您。另外两个答案也是正确的。 - Umer Waheed

1
你可以使用一个视图模型
public class MyViewModel
{
   public Caller Caller { get; set; }
   public Receiver Receiver { get; set; }
}

然后您可以这样填充视图模型:
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);
}

查看:

@model MyViewModel
<h1>@Model.Caller.Title</h1>
@if(Model.Receiver != null) {
   <h1>@Model.Receiver.Title</h1>
}

0

最干净的方法是通过视图模型传递:

  • 视图模型
public class MyViewModel {
    public Caller MyCaller { get;set; }
    public Receiver MyReceiver { get;set; }
}
  • 控制器
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);
}
  • 查看
@model MyViewModel

<h1>@Model.MyCaller.Id</h1>
<h1>@Model.MyReceiver.Id</h1>

感谢您的回答。 - user4863604

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接