开发者

ASP.NET MVC 2: multiple checkboxes against a Model?

开发者 https://www.devze.com 2023-02-03 07:47 出处:网络
I\'m trying to wrap my head around a Model that allows for multiple checkbox options. For example, say I\'ve got a group called \"ValidTimes\" ... I\'ve then got checkboxes for all of the ValidTimes

I'm trying to wrap my head around a Model that allows for multiple checkbox options.

For example, say I've got a group called "ValidTimes" ... I've then got checkboxes for all of the ValidTimes that should be saved.

Right now, my Model has a string ValidTimes { get; set; } but I'm not sure how I'm supposed to check more than 1 value against my model...

Not to mention validating against that model to make sure that ther开发者_开发知识库e is at least one value selected.

Should my Model consist of all possible options within that Checkbox group?


Just off the top of my head, I think this should work:

Change ValidTimes to a string array. Use a loop to generate a checkbox for each possible time, giving the checkbox the name of the time period (or some unique value that you can equate to a specific time period), then use a custom model binder to read the form values from the HTTP Post and add the names of the checked check boxes to the string array.

I'm still a relative MVC novice so there may be an easier way, but this is how I would approach it.

EDIT: Below post on SO takes a similar approach to that suggested above but also provides code samples. ASP.Net MVC - Handle Multiple Checkboxes


This is quite an extensive issue. I have figured out how to not only post the state of each checkbox, but also retain the state when returning to the View.

Radio buttons tended to be the biggest pain, but by using a string property as a placeholder for the radio button value, you are able to retain that state as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消