asp.net mvc - pass partial data model to partial view

后端 未结 2 1958
轮回少年
轮回少年 2021-02-08 23:51

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

At the view:

@model IEnumerable

        
相关标签:
2条回答
  • 2021-02-09 00:12

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

    then a view:

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

    and finally you could define a corresponding display template which will automatically be rendered for each element of the Brands collection of your view model (~/Views/Shared/DisplayTemplates/Brand.cshtml):

    @model Brand
    <tr>
        <td>
            @Html.DisplayForModel()
        </td>
    </tr>
    
    0 讨论(0)
  • 2021-02-09 00:12

    For 1 try changing @Html.RenderPartial("_DisplayAttribute",Brand) to @Html.Partial("_DisplayAttribute",Brand)

    You will also need to specify the model in the partial view like @model products_comparison.Models.Brand or something like it

    Also please clarify 2 & 3 as they are not clear what you want

    0 讨论(0)
提交回复
热议问题