This might be a first, but I actually stole this from myself off Stackoverflow. Posted it and thought it might be useful to share with the 1 live person who reads this blog and the 90 other bots… And I’m not sure about the 1 live person.
So here’s the situation, it’s late, you’ve got a strongly typed view that has a checkbox list, and you are desperate for an answer on how to handle it…. and now you’re scraping the bottom of the barrel. Well, good news is, I have the answer.
Let’s say you have a Book class that has a list of Categories. The Category class is simple, just has an id and name.
public class Book { public Int32 BookId { get; set; } public IList<Category> Categories { get; set; } } public class Category { public Int32 Id { get; set; } public String Name { get; set; } }
Now you could try and figure out a way to create a typed view using the Book class. You could also stomp on your left foot until it bleeds. Who am I to judge you for liking pain? (Sick f—) For those who don’t want to go through that nightmare, I have an alternative: Create two new classes, one to set the view and one to handle the post back.
public class ViewBookModel { public ViewBookModel(Book book, IList<Categories> categoryList) { BookId = book.Id; CategoryList = categoryList; } public Int32 BookId { get; private set; } IList<Categories> CategoryList { get; set; } }
First the class to set the view. As you can see, there is a book id that corresponds to a book object’s id (DUH) and the category list which you will set in the original action.
[AcceptVerbs(HttpVerbs.Get)] public ActionResult EditBook(Int32 bookId) { Book foundBook = Book.GetById(bookId); IList<Category> categoryList = Category.GetAll(); ViewBookModel model = new ViewBookModel(foundBook, categoryList); return View(model); }
And then your markup for the checkbox list will be something like this:
<% foreach(var category in Model.CategoryList) { %> <input type="checkbox" name="CategoryIds" value="<%= category.Id %>" /> <% } %>
Notice that the name for every input is CategoryIds. This is because this will be the name of the collection of ids on the model for posting:
public class ViewBookInModel { public String BookId { get; set; } public Int32[] CategoryIds { get; set; } }
And the action method would look like:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult UpdateBook(ViewBookInModel book) { foreach(Int32 id in book.CategoryIds) { ... } }
And boom, problem solved. You can now use a strongly typed View with a checkbox list. Go forth and be fruitful.
Hi!
Congratulations! Your readers have submitted and voted for your blog at The Daily Reviewer. We compiled an exclusive list of the Top 100 Programming Blogs, and we are glad to let you know that your blog was included! You can see it at http://thedailyreviewer.com/top/programming/2
You can claim your Top 100 Blogs Award here : http://thedailyreviewer.com/pages/badges/programming
P.S. This is a one-time notice to let you know your blog was included in one of our Top 100 Blog categories. You might get notices if you are listed in two or more categories.
P.P.S. If for some reason you want your blog removed from our list, just send an email to angelina@thedailyreviewer.com with the subject line “REMOVE” and the link to your blog in the body of the message.
Cheers!
Angelina Mizaki
Selection Committee President
The Daily Reviewer
http://thedailyreviewer.com
Can you post the sourc code please
Can you post the source code please
This works great until you introduce validation.
Does this preserve value of checkbox after postback ? In my case it works fine but it dont keep checkboxes checked after postback.
Thanks!
You’ll have to set them using your model. If you are new to MVC (And sorry if you aren’t I might just be misunderstanding what you’re asking), you might be used to viewstate holding values. In MVC, you are responsible for setting the values of the check boxes yourself using your model or other, personally speaking, less elegant ways. You will lose all values on the page if you don’t.
Thanks help me with these checkboxes.
1 person reporting… :p
i have a table in data base and that table name is “screen” which contains “screenid” and “screenname” i have to show the screen name dynamically in checkboxes in the view,means it should come from the table in the database.in that view i have a text box for “rolename”where rolename belongs to the another table “role”.when i am going to add some role ,i have to check the screens ,so that screens should be permitted to that perticular role,how to do all these things in mvc,i am not getting?please give me some solutions
thanks & regards
Debasish Mishra
mail id: mishra.debasish@gssinfotech.com
Are you talking about applying view permissions to a page?
Hi,this is debasish here.
I have an requirement and I am not getting any ideas on how to implement it?i am giving you a clear picture over here.
in view:
rolename:one textbox should be here
some checkboxes whose names come from screen database
and one button
so,when the button is clicked the action should postback and should make crud operation .
That is suppose I have a database where 3 tables are present
Screenid screenname
1 Screen1
—————– ——————————
—————– ——————————-
TABLE:1
roleid rolename
1 admin
2 User1
TABLE2
id screenid roleid
1 1 1
2 2 1
TABLE3
Here when the administrator is going to supply the rolename while checking the screen then those screen should privileged with that user.
How to do it?i am not getting any idea how to dynamically bind the screen names with checkboxes,please help me!!!!
Thanks & regards
Debasish Mishra
Holy Crap Balls you saved my head from exploding! Thank You!
I do what I can to help prevent exploding heads.
Thanks for sharing. Make this a habit!
It saved me a lot of time.
Sharing is caring.
Thank you!! Perfect solution and you taught me a couple things I didn’t know about MVC!!
Might be a stupid question, but I coudn’t catch: where the ViewBookInModel instance was created and initialized for Post action (with BookId and CategoriesIds properties) ?
Thanks in advance.
Oh, thank you so much. I jumped head-first into an MVC gig when I discovered that I no longer knew how to read the values from a freaking list of checkboxes. Smashing my face repeatedly against my new cubicle wall turned out to be ineffective. Thank you for showing me a better way.