asp.net mvc的 - 传递部分数据模型的局部视图 [英] asp.net mvc - pass partial data model to partial view

查看:170
本文介绍了asp.net mvc的 - 传递部分数据模型的局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个得到一个模型列的局部视图,并打印出来。
这样的事情:

I wish to build a partial view that gets a model column and print it. Something like that:

目前的看法:

@model IEnumerable<products_comparison.Models.Product>
@{
ViewBag.Title = "Index";

var Brand = (from r in Model
             select r.Brand).Distinct();
}
<h2>
Index</h2>

@Html.RenderPartial("_DisplayAttribute",Brand)

和在局部视图:

<table>
    <tr>
        <th>
            Brand
        </th>
    </tr>
    @foreach (var row in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(r => row)
            </td>
        </tr>
    }
</table>

有我遇到了几个问题:


  1. 编译犯规让我送Barnd的局部视图。

  2. 如果你看一下局部视图code,你会看到这个词的品牌,这是列名。我不希望硬codeD中的局部视图中的品牌一词,而不是我喜欢的列名会在那里。

  3. 在局部视图我需要把@model products_comparison.Models.Product,但我不
    要发送的孔表。我想给只有一列 - 但我不知道要放什么东西有..

谢谢!

编辑:

只是为了澄清一件事,我想该视图将(反正大多数在表中的列)调用表中的每一列的相同的​​局部视图,每一次,我会送不同的列(不同的价值列是精确的)。

Just to clear one thing, I want that the view will call the same partial view for each column in the table(for most of the columns in the table anyway) and each time I'll send a different column(distinct value column to be exact).

推荐答案

通过重构启动,并把正确的逻辑放到正确的地方。此LINQ查询有没有严格在视图中做。视图是不应该做任何LINQ查询或其他提取数据。视图应该与它的图模型的形式下传递给它从控制器动作数据进行工作。一个控制器动作生成和传递您定义的视图中调整视图模型。

Start by refactoring and putting the right logic into the right place. This LINQ query has strictly nothing to do in a view. A view is not supposed to do any LINQ queries or whatever to pull data. A view is supposed to work with data that it is passed to it from the controller action under the form of a view model. A controller action builds and passes an adapted view model that you define for the view.

,以便始终可以通过定义将要适应你观的要求视图模型启动:

So as always you start by defining a view model that will be adapted to the requirements of your view:

public class MyViewModel
{
    public IEnumerable<Brand> Brands { get; set; } 
}

那么你就写一个控制器的动作,将填充这个视图模型,并将其传递给视图:

then you write a controller action that will populate this view model and pass it to the view:

public ActionResult Foo()
{
    IEnumerable<products_comparison.Models.Product> products = ...
    var model = new MyViewModel
    {
        Brands = (from r in Model select r.Brand).Distinct()
    };
    return View(model);
}

再一个观点:

@model MyViewModel
<table>
    <tr>
        <th>
            Brand
        </th>
    </tr>
    @Html.DisplayFor(x => x.Brands)
</table>

最后,你可以定义将自动被渲染为您的视图模型的品牌集合(中的每个元素相应的显示模板〜/查看/共享/ DisplayTemplates / Brand.cshtml

@model Brand
<tr>
    <td>
        @Html.DisplayForModel()
    </td>
</tr>

这篇关于asp.net mvc的 - 传递部分数据模型的局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆