【问题标题】:C# Linq Query - Return results to ViewC# Linq 查询 - 将结果返回到视图
【发布时间】:2014-08-10 19:18:21
【问题描述】:

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

【问题讨论】:

  • 什么是webService2?为什么不使用webService.AllProducts(1); 的结果?它会返回任何结果吗?为什么要静音所有异常?
  • 对不起,这是一个错字,应该是网络服务,目前,我没有收到任何错误,并且更关心如何将这些项目传递到我的视图中。我打算添加错误,但我正在调试,所以当事情失败时我似乎能够捕捉到

标签: c# asp.net asp.net-mvc-3 linq-to-sql


【解决方案1】:

您的实体名称确实令人困惑,为什么“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 而不是在代码中创建特定对象。此外,您不需要添加视图的相对路径,只需为控制器创建相同的文件夹层次结构。

这是您的模型代码 (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>
}

【讨论】:

    猜你喜欢
    • 2014-09-05
    • 2016-09-30
    • 2010-09-25
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多