简体   繁体   English

如何将表联接传递到ASP.net中的视图

[英]How to pass a table join to my view in ASP.net

I am new to C# and asp.net and mvc. 我是C#,asp.net和mvc的新手。 I am trying to figure out how to pass my data from my controller to my view. 我试图弄清楚如何将数据从控制器传递到视图。 I got it working with one table, but I need more info. 我可以在一张桌子上工作,但是我需要更多信息。

My controller 我的控制器

namespace OpenCustomerOrders.Controllers
{
    public class OrderController : Controller
    {

        OrderContext db = new OrderContext();
        public ActionResult Index()
        {
            var query = (from h in db.oeordhdr_sql
                         join l in db.oeordlin_sql
                         on h.ord_no equals l.ord_no
                         select new
                         {
                             h.ord_no,
                             h.ship_via_cd,
                             h.bill_to_name,
                             l.item_no,
                             l.qty_ordered,
                             l.item_desc_1,
                         }).ToList();


            return View(query);
        }
    }
}

My view right now looks like 我现在的视像

@model IEnumerable<OpenCustomerOrders.oeordhdr_sql>

@{
    ViewBag.Title = "Index";
}

 <th>Bill to Name</th>

 <td>
            @Html.DisplayFor(modelItem => item.ord_no)
        </td>

You need to create a ViewModel here and add properties in it which are needed to be displayed on the view, which would look like: 您需要在此处创建一个ViewModel并在其中添加需要在视图上显示的属性,如下所示:

public class OrdersViewModel
{

  public int ord_no { get;set; }
  public int item_no { get;set; }
  // other properties needed
  .................
  .................                       
}

and then in your linq query you would project with that class instance like: 然后在linq查询中,您将使用该类实例进行投影,例如:

public ActionResult Index()
{
     var query = (from h in db.oeordhdr_sql
                  join l in db.oeordlin_sql
                  on h.ord_no equals l.ord_no
                  select new OrdersViewModel
                  {
                      ord_no = h.ord_no,
                      .........
                      .........
                      item_no = l.item_no
                  }).ToList();


     return View(query);
}

and now in View change the model to new viewmodel : 现在在View中将模型更改为new viewmodel:

@model IEnumerable<OpenCustomerOrders.OrdersViewModel>

@{
    ViewBag.Title = "Index";
}

 <th>Bill to Name</th>

 <td>@Html.DisplayFor(modelItem => item.ord_no)</td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM