如何在ASP.Net MVC中制作复选框列表

时间:2016-06-12 19:53:53

标签: c# asp.net asp.net-mvc

我有一个带有复选框列表的表单。用户可以选择所有值,没有值或其间的任何值。例如:

screenshot of Goal

我想将结果作为逗号分隔列表写入数据库。在上面的例子中," Apple,Banana"。我有点困惑如何为此创建模型以及如何将View到Controller的结果转换为以逗号分隔的列表?

2 个答案:

答案 0 :(得分:65)

这是一个如何做到这一点的例子。

HomeModel.cs

public class HomeModel
{
    public IList<string> SelectedFruits { get; set; }
    public IList<SelectListItem> AvailableFruits { get; set; }

    public HomeModel()
    {
        SelectedFruits = new List<string>();
        AvailableFruits = new List<SelectListItem>();
    }
}

HomeController.cs

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new HomeModel
        {
            AvailableFruits = GetFruits()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(HomeModel model)
    {
        if (ModelState.IsValid)
        {
            var fruits = string.Join(",", model.SelectedFruits);

            // Save data to database, and redirect to Success page.

            return RedirectToAction("Success");
        }
        model.AvailableFruits = GetFruits();
        return View(model);
    }

    public ActionResult Success()
    {
        return View();
    }

    private IList<SelectListItem> GetFruits()
    {
        return new List<SelectListItem>
        {
            new SelectListItem {Text = "Apple", Value = "Apple"},
            new SelectListItem {Text = "Pear", Value = "Pear"},
            new SelectListItem {Text = "Banana", Value = "Banana"},
            new SelectListItem {Text = "Orange", Value = "Orange"},
        };
    }
}

Index.cshtml

@model DemoMvc.Models.HomeModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        @using (Html.BeginForm("Index", "Home"))
        {
            foreach (var item in Model.AvailableFruits)
            {
                <div class="checkbox">
                    <label>
                        <input type="checkbox"
                               name="SelectedFruits"
                               value="@item.Value"
                               @if(Model.SelectedFruits.Contains(item.Value))
                               {
                                   <text> checked </text> 
                               } 
                               /> @item.Text
                        </label>
                    </div>
            }
            <div class="form-group text-center">
                <input type="submit" class="btn btn-primary" value="Submit" />
            </div>
        }
    </div>
</body>
</html>

在Post Action中应该产生以下结果:

Post Action

答案 1 :(得分:1)

您也可以使用jquery。无需更改任何控制器或操作。它只需在数据库表的列中添加逗号分隔的选定复选框值即可,只需在视图页面中添加代码即可。

 <div class="editor-field">

        @Html.HiddenFor(model => model.hobbies, new { htmlAttributes = new { id = "hobbies" } })
        Hobbies :
        <input type="checkbox" id="r" onchange="getSelected()" value="Reading" />
        Reading
        <input id="w" type="checkbox" value="Writing" onchange="getSelected()" />
        Writing

        <script>
            function getSelected() {
                var sList = "";
                $('input[type=checkbox]').each(function () {
                    if (this.checked) {
                        sList += this.value + ",";

                    }
                });
                $("#hobbies").val(sList);
            }
        </script>
        @Html.ValidationMessageFor(model => model.hobbies)
    </div>