Reputation: 4873
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);
}
Upvotes: 0
Views: 927
Reputation: 6658
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>
}
Upvotes: 1