2

I have a table in my dbml called Product.

In my Controller I have the following LINQ...

public ActionResult Index(int id)
    {
        using (orbitDataContext = new OrbitDataContext())
        {
            var products = (from p in orbitDataContext.Products
                            where p.EventId == id
                            select p).ToList();

            return View(products);
        }
    }

In my View I have the following...

@model IList<MVC.Product>

@{
    ViewBag.Title = "Products";
}

<h2>Products</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<p>
    <input type="submit" value="Delete Selected" />
</p>

@foreach (var item in Model)
{
    <ul>
        <li>@item.Description | @item.ProductCode | @item.Price</li>
    </ul> 
}

Please can somebody explain how I can display a check box against each product displayed so a user can check multiple products then click a button which sends the selected products back to my controller in order for me to delete them.

Csharp
  • 2,916
  • 16
  • 50
  • 77
Jonno Lord
  • 314
  • 1
  • 3
  • 14

1 Answers1

1

Just a couple of pointers before I get to a potential answer.

Don't return your domain model to the view, rather use a view model.

public class YourViewModel
{
     public List<Product> Products { get; set; }
}

Separate you data retrieval from your controller, something like this:

public ActionResult YourActionMethod()
{
     YourViewModel viewModel = new YourViewModel
     {
          Products = productService.FindAll()
     }

     return View(viewModel);
}

In your view can try something like this:

<ul>
     @for (int i = 0; i < Model.Products.Count(); i++)
     {
          <li>
               @Html.CheckBoxFor(x => x.Products[i].IsSelected)
               @Html.DisplayFor(x => x.Products[i].Description) @Html.HiddenFor(x => x.Products[i].Description)
               @Html.DisplayFor(x => x.Products[i].ProductCode) @Html.HiddenFor(x => x.Products[i].ProductCode)
               @Html.DisplayFor(x => x.Products[i].Price) @Html.HiddenFor(x => x.Products[i].Price)
          </li>
     }
</ul>

This might not be perfect but it can help you on your way. Hope it helps.

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234