【问题标题】:How to pass more than one object to the view in mvc?如何将多个对象传递给mvc中的视图?
【发布时间】:2016-01-14 01:30:44
【问题描述】:

我想在视图中传递多个对象。我有两个对象。一个名字是“来电者”,一个名字是“接收者”。我是 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。

标签: asp.net-mvc


【解决方案1】:

是的,您可以这样做。有多种方法可以做到这一点。

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

可以看here看mvc中viewBag的使用方法

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

3) 你可以像下面这样制作 ViewModel(推荐)

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

现在将 callerReciver 传递给 view。你可以访问这两个 object。希望你能理解。

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

【讨论】:

  • 谢谢。我知道如何通过,但额外的知识对我也有帮助。再次感谢
  • 不客气。其他两个答案也是对的。
【解决方案2】:

您可以使用View Model

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>
}

【讨论】:

    【解决方案3】:

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

    • 视图模型
    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>
    

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多