【问题标题】:Sending IEnumerable to a view that already contains a model将 IEnumerable 发送到已经包含模型的视图
【发布时间】:2012-12-04 14:02:19
【问题描述】:

这是视图:

@model tgpwebged.Models.sistema_DocType
 ...

此模型是与 textBoxFor 和其他 html 助手一起使用的实体

这是控制器。

public ActionResult AdminSettingAddTipo()
{
    IEnumerable<string> indices;

    using (tgpwebgedEntities context = new tgpwebgedEntities())
    {
        var obj = from u in context.sistema_Indexes select u.idName;
         indices = obj.ToList();
    }

    return PartialView(indices);
}

我这里有我需要的一切,我正在使用一个模型来创建视图,因此我不能将“索引”作为模型发送,因为一个视图中不允许有 2 个模型。

我现在不想使用“Tupe”作为父视图。我只想知道如何将我的 IEnumerable 发送到视图的最佳方式。

我正在考虑将 ViewBag 作为最后一个选项,但我正在避免使用 ViewBag。

谢谢

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    ViewBag 不是一个好的选择。使用您的列表和当前模型创建 ViewModel:

        public class YourViewModel
        {
    
            public sistema_DocType Type { get; set; }
            public IEnumerable<string> Indices {get;set;}
        }
    

    希望,它会有所帮助。

    【讨论】:

    • 我总是将自己的构造函数写成这样的类,并使用它。
    【解决方案2】:

    如果您出于某种原因不想使用 ViewBag,则可以专门为包含旧模型信息和所需新索引的视图创建一个模型。这是 MVC 开发中的常见模式。您甚至可以让 ViewModel 成为当前模型的装饰器。

    http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

    【讨论】:

      【解决方案3】:

      尽可能使用强定义,将其应用于模型并发送该模型:

      型号

      public class MyModel{
           public List<sistema_Indexes> indecies {get;set;}
      
      }
      

      控制器

      MyModel model = new MyModel();
      model.indecies = context.sistema_Indexes.Select(u=> u.idName).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-14
        • 2017-07-27
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        • 2016-10-04
        相关资源
        最近更新 更多