MVC 4多选列表框和选中列表框

时间:2013-01-11 08:36:56

标签: asp.net-mvc-4 multi-select html.listboxfor

我想在Sivaraman Dhamodharan在MVC 4 asp.net中执行类似的实现,他的文章发现于:http://www.codeproject.com/Articles/139792/Multi-Select-List-Box-and-Checked-List-Box

我是MVC 4的新手,我很享受!

1 个答案:

答案 0 :(得分:-1)

您可以在MVC中轻松地为“访问区域”和“已分配的ID”创建多选框(如您在文章中所述)。对于带有复选框的选择框,您可以在MVC中创建表。

请按照以下步骤操作。

假设页面的视图模型是AssignWorkViewModel,产品的视图模型是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; }
}

假设操作方法名称为“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);
    }

观点,

@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>

结果,

enter image description here

我认为这可能会帮助你开始。