开发者

how can print value of two columns of a table

开发者 https://www.devze.com 2023-03-16 06:24 出处:网络
I am working on MVC3 asp.net. this is my sr=tatement in controller:- ViewBag.rawMaterialRequired = (from x in db.RawMaterial

I am working on MVC3 asp.net. this is my sr=tatement in controller:-

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

this is my code in View:-

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

this is my output:-

{ Description = Polymer 26500, Quantity = 10 }
{ Description = Polymer LD-M50, Quantity = 10 }
{ Description = Titanium R-104, Quanti开发者_开发问答ty = 20 }

this is my desired output:-

how can print value of two columns of a table


Start by designing a view model:

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

then in your controller use this view model:

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

and inside the view:

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

That's was the first step into improving your code. The second step consists of getting rid of ViewBag and use strongly typed views and display templates:

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

and in the view remove any ugly loops thanks to display templates:

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

and inside the display template (~/Views/Shared/DisplayTemplates/ProductLineViewModel.cshtml):

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

精彩评论

暂无评论...
验证码 换一张
取 消