Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);
}
share|improve this question
    
What is webService2? Why don't you use results of webService.AllProducts(1);? Does it return any results? Why do you mute all exceptions? –  Ilya Luzyanin yesterday
    
Sorry, that is a typo, it should be web service, currently, I'm not getting any errors, and am more concerened with understanding how to pass these items into my view. I plan to add errors, but I'm debugging as I go, so I seem to be able to catch when things fail –  Mark Roberts yesterday
    

1 Answer 1

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>
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.