MVC 4 Multi-Select List Box and Checked List Box

Levi Nkata picture Levi Nkata · Jan 11, 2013 · Viewed 12.2k times · Source

I want to do a similar implementation done by Sivaraman Dhamodharan in MVC 4 asp.net in his article found on: http://www.codeproject.com/Articles/139792/Multi-Select-List-Box-and-Checked-List-Box

I am new in MVC 4 and I'm enjoying it!

Answer

Haritha picture Haritha · Jan 11, 2013

You can create Multi-Select boxes for "Visit Area" and "Assigned Id" (as mentioned in the article you have put) very easily in MVC. For the select box with the checkboxes, you can create a table in MVC.

Please follow the steps below.

Let's assume that that the view model for the page is AssignWorkViewModel and the view model for the product is ProductViewModel.

public class AssignWorkViewModel
{

    public List<ProductViewModel> Products { get; set; }
}


public class ProductViewModel
{
    public int ProductId { get; set; }

    //used to bind the checkbox value in the view
    public bool IsSelected { get; set; }

    public string ProductName { get; set; }
}

Let's assume that the action method name is "AssignWork"

public ActionResult AssignWork()
    {
        AssignWorkViewModel model = new AssignWorkViewModel();

        List<ProductViewModel> products = new List<ProductViewModel>();

        //let's add some values
        ProductViewModel samsungMonitor = new ProductViewModel();
        samsungMonitor.ProductId = 1;
        samsungMonitor.IsSelected = false;
        samsungMonitor.ProductName = "Samsung Monitor";
        products.Add(samsungMonitor);

        ProductViewModel sonyDvd = new ProductViewModel();
        sonyDvd.ProductId = 2;
        sonyDvd.IsSelected = false;
        sonyDvd.ProductName = "Sony DVD";
        products.Add(sonyDvd);

        ProductViewModel motherBoard = new ProductViewModel();
        motherBoard.ProductId = 3;
        motherBoard.IsSelected = false;
        motherBoard.ProductName = "Pentium Mother Board";
        products.Add(motherBoard);

        model.Products = products;

        //pass model to the view
        return View(model);
    }

The View,

@model SelectBoxTest.ViewModels.AssignWorkViewModel
<table>
    @foreach (var item in Model.Products)
    {
        <tr>
            <td>@Html.HiddenFor(model => item.ProductId)</td>
            <td>@Html.CheckBoxFor(model => item.IsSelected)</td>
            <td>@Html.DisplayFor(model => item.ProductName)</td>
        </tr>
    }
</table>

The result,

enter image description here

I think this might help you to start.