【问题标题】:how can print value of two columns of a table如何打印表格两列的值
【发布时间】:2011-06-29 06:24:18
【问题描述】:

我正在研究 MVC3 asp.net。 这是我在控制器中的 sr=statement:-

ViewBag.rawMaterialRequired = (from x in db.RawMaterial 
 join y in db.ProductFormulation on x.ID equals y.RawMaterialID 
 where y.ProductID == p select new { x.Description, y.Quantity });

这是我在视图中的代码:-

 @foreach(var album in ViewBag.rawMaterialRequired)
         {
                @album<br />
         }
         </div>

这是我的输出:-

{ Description = Polymer 26500, Quantity = 10 }
{ Description = Polymer LD-M50, Quantity = 10 }
{ Description = Titanium R-104, Quantity = 20 }

这是我想要的输出:-

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 razor


    【解决方案1】:

    从设计一个视图模型开始:

    public class ProductLineViewModel
    {
        public string Description { get; set; }
        public int Quantity { get; set; }
    }
    

    然后在你的控制器中使用这个视图模型:

    ViewBag.rawMaterialRequired = 
         from x in db.RawMaterial 
         join y in db.ProductFormulation on x.ID equals y.RawMaterialID 
         where y.ProductID == p 
         select new ProductLineViewModel 
         { 
             Description = x.Description, 
             Quantity = y.Quantity 
         };
    

    在视图内部:

    <table>
        <thead>
            <tr>
                <th>Description</th>
                <th>Quantity</th>
            </tr>
        </thead>
        <tbody>
        @foreach(var product in (IEnumerable<ProductLineViewModel>)ViewBag.rawMaterialRequired)
        {
            <tr>
                <td>@product.Description</td>
                <td>@product.Quantity</td>
            </tr>
        }
        </tbody>
    </table>
    

    这是改进代码的第一步。第二步包括摆脱ViewBag 并使用强类型视图和显示模板:

    public ActionResult Foo()
    {
        var model = 
             from x in db.RawMaterial 
             join y in db.ProductFormulation on x.ID equals y.RawMaterialID 
             where y.ProductID == p 
             select new ProductLineViewModel 
             { 
                 Description = x.Description, 
                 Quantity = y.Quantity 
             };
        return View(model);
    }
    

    并在视图中删除所有丑陋的循环,这要归功于显示模板:

    @model IEnumerable<ProductLineViewModel>
    <table>
        <thead>
            <tr>
                <th>Description</th>
                <th>Quantity</th>
            </tr>
        </thead>
        <tbody>
            @Html.DisplayForModel()
        </tbody>
    </table>
    

    在显示模板内(~/Views/Shared/DisplayTemplates/ProductLineViewModel.cshtml):

    @model ProductLineViewModel
    <tr>
        <td>@Html.DisplayFor(x => x.Description)</td>
        <td>@Html.DisplayFor(x => x.Quantity)</td>
    </tr>
    

    【讨论】:

    • 先生,非常感谢您的帮助,对于您的帮助,我真的无法表达我的高兴。上帝赐予你生活中的所有幸福......先生,你真的为我做了非常非常有价值的工作。再次感谢...
    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 2020-03-30
    • 2015-04-11
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多