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

nbewdwxp  于 2023-08-08  发布在  .NET
关注(0)|答案(3)|浏览(129)

我有一个带有复选框列表的窗体。用户可以选择所有值、不选择值或两者之间的任意值。范例:


的数据
我想将结果以逗号分隔的列表的形式写入数据库。在上面的例子中,“苹果,香蕉”。我有点困惑,该如何为此创建模型,以及如何将结果从视图到控制器放到一个逗号分隔的列表中?

vbopmzt1

vbopmzt11#

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

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>


这应导致“后操作”中的以下结果:


的数据

hfyxw5xn

hfyxw5xn2#

你也可以使用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>

字符串

8zzbczxx

8zzbczxx3#

所以我在一个相当愚蠢的问题上撞到了墙上…确保你使用的所有东西都是属性而不是变量。比如...
Model.Variable.VariableList<string>可能会在加载页面时呈现...但是,当您提交页面时,不会返回值。
Model.Property.PropertyList<string>可以工作。
再清楚一点…

public class MyListClass 
{
  public string MyListName { get; set; } = "My List Name";

//next line will show your items, but will not have changes to the items
//returned because it's not a property aka with getter and setter.
  public List<CheckBoxItem> Items = new List<CheckBoxItem>;
}

public class MyModel
{
//next line will show your items, but will not have changes to the items
//returned because it's not a property aka with getter and setter.
  public MyListClass MyList = new MyListClass();

}

字符串
正确的方法是...

public class MyListClass 
{
  public string MyListName { get; set; } = "My List Name";

  public List<CheckBoxItem> Items { get; set; } = new List<CheckBoxItem>;
}

public class MyModel
{
  public MyListClass MyList { get; set; } = new MyListClass();

}


我意识到我的...情报显示但对于那些也把你的头撞在世界上每一个不起作用的例子上的人,我希望这对你有帮助。

相关问题