c# – 如何使ASP.Net MVC中的复选框列表

前端之家收集整理的这篇文章主要介绍了c# – 如何使ASP.Net MVC中的复选框列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有复选框列表的表单.用户可以选择所有值,无值,或两者之间的任何值.例:

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

解决方法

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

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" /> @item.Text
                        </label>
                    </div>
            }
            <div class="form-group text-center">
                <input type="submit" class="btn btn-primary" value="Submit" />
            </div>
        }
    </div>
</body>
</html>

哪些应该在邮政行动中导致以下内容

猜你在找的C#相关文章