简体   繁体   中英

C# Linq Query - Return results to View

I'm very new to c#

I have the following linq query:

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

All I want to be able to do is call this from my controller and create a list for each product group returned and load it into my view.

My controller is as follows, but I have no clue how to create a list, and pass it to my view, I'm very confused.

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

Your entity name is really confusing why "GetAllProducts" it sounds like a function to me... I renamed it to Product. The new repository code:

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

Your Controller almost good, just rename the Entity and I suggest to use DI instead of creating specific object in the code. Also you don't need to add the relative path of the View just create the same folder hierarchy for the Controller.

Here is your model code (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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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