lundi 6 janvier 2020

Using ASP.NET MVC CheckBoxFor in a list

I'm trying to create a simple scrollable list of checkboxes in ASP.NET MVC 5. I got a single checkbox to work and it correctly posts back the right value to model.Checked:

Controller

using System.Web.Mvc;
using Checkbox1.Models;

namespace Checkbox1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new TestModel
            {
                Checked = true
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(TestModel model)
        {
            return View(model);
        }
    }
}

View

@model Checkbox1.Models.TestModel


@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{

    @Html.CheckBoxFor(m => m.Checked, Model.Checked)

    <input type="submit" value="submit" />

}

Model

namespace Checkbox1.Models
{

    public class TestModel
    {
        public bool Checked { get; set; }

    }

}

But when I try the same thing with a list of bools I can't get the bool value to pass back into the Controller. It looks like the model is getting re-instantiated and nulled out when it gets posted back to the Controller:

Controller

using System.Collections.Generic;
using System.Web.Mvc;
using Checkbox2.Models;

namespace Checkbox2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new TestModel()
            {
                lstChecked = new List<bool>()
            };

            model.lstChecked.Add(true);

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(TestModel model)
        {
            return View(model);
        }


    }
}

View

@model Checkbox2.Models.TestModel


@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{

    @Html.CheckBoxFor(m => m.lstChecked[0], Model.lstChecked[0])

    <input type="submit" value="submit" />

}

Model

using System.Collections.Generic;
using System.Web;

namespace Checkbox2.Models
{
    public class TestModel
    {
        public List<bool> lstChecked;

    }

}

I'd like to know why this is not working but if you could point me to a simple working example of a scrollable list of checkboxes that would also be greatly appreciated!




Aucun commentaire:

Enregistrer un commentaire