ASP.NET MVC Multiple Checkboxes

后端 未结 3 1440
-上瘾入骨i
-上瘾入骨i 2020-12-29 13:22

I have a List of about 20 items I want to display to the user with a checkbox beside each one (a Available property on my ViewModel).

When

相关标签:
3条回答
  • 2020-12-29 13:54

    This blog post also could help;

    http://tugberkugurlu.com/archive/how-to-handle-multiple-checkboxes-from-controller-in-asp-net-mvc-sample-app-with-new-stuff-after-mvc-3-tools-update

    0 讨论(0)
  • 2020-12-29 13:57

    The best thing to do would be to create a template that can be reused. I have some code at home that I can post later tonight.

    Maybe check SO for similar posts in the mean time.

    Dynamic list of checkboxes and model binding

    0 讨论(0)
  • 2020-12-29 14:09

    Model:

    public class MyViewModel
    {
        public int Id { get; set; }
        public bool Available { get; set; }
    }
    

    Controller:

    public class HomeController: Controller
    {
    
        public ActionResult Index()
        {
            var model = Enumerable.Range(1, 20).Select(x => new MyViewModel
            {
                Id = x
            });
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(IEnumerable<MyViewModel> model)
        {
            ...
        }
    }
    

    View ~/Views/Home/Index.cshtml:

    @model IEnumerable<AppName.Models.MyViewModel>
    @using (Html.BeginForm())
    {
        @Html.EditorForModel()
        <input type="submit" value="OK" />
    }
    

    Editor template ~/Views/Home/EditorTemplates/MyViewModel.cshtml:

    @model AppName.Models.MyViewModel
    @Html.HiddenFor(x => x.Id)
    @Html.CheckBoxFor(x => x.Available)
    
    0 讨论(0)
提交回复
热议问题