簡體   English   中英

C#Linq查詢-將結果返回到View

[英]C# Linq Query - Return results to View

我是C#的新手

我有以下linq查詢:

public GetAllProducts[] AllProducts(int status)
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts.Where(x => x.Status == status).Select(x => new GetAllProducts { Name = x.Name, Desc = x.Description, Price = x.Price }).OrderBy(x => x.Name).ToArray();
        }
    }
    catch
    {
        return null;
    }
}

我想要做的就是從控制器中調用此方法,並為返回的每個產品組創建一個列表,並將其加載到我的視圖中。

我的控制器如下,但是我不知道如何創建列表並將其傳遞給我的視圖,我很困惑。

public ActionResult Index(GetAllProducts allProductsModel)
{
    var webService = new DaveyServiceClient();
    webService.AllProducts(1);
    var allProducts = webService2.AllProducts();
    return View("../Private/Index", allProducts);
}

您的實體名稱確實讓我感到困惑,為什么“ GetAllProducts”對我來說像個函數……我將其重命名為Product。 新的存儲庫代碼:

public Ienumerable<Product> AllProducts(int status)
    {
        try
        {
            using (UserDataDataContext db = new UserDataDataContext())
            {
                return db.mrobProducts.Where(x => x.Status == status).Select(x => new Product
                {
                    Name = x.Name,
                    Desc = x.Description,
                    Price = x.Price
                }).OrderBy(x => x.Name);
            }
        }
        catch
        {
            return null;
        }
    }

您的控制器幾乎不錯,只需重命名實體,我建議使用DI而不是在代碼中創建特定的對象。 另外,您無需添加視圖的相對路徑,只需為Controller創建相同的文件夾層次結構即可。

這是您的模型代碼(cshtml):

@model IEnumerable<Product>

@{
    ViewBag.Title = "All Products";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@foreach (var item in Model)
{
   //Show your products
   <p>item.Name</p>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM