Using a dynamic list of checkboxes in a view, how to create the model - asp.net-mvc

I have an asp mvc 2 app lication where I want to display a list of check boxes that a user can select, based on a list of records in a database. To display the list my model contains a List object and the view has a foreach, and outputs Html.CheckBox for each item in the list.
Is there a way to get the model populated with the selected checkboxes, given that the model can't have specific properties for each checkbox, because the list is dynamic? Or do I have to manually iterate through the forms variables myself?
Edit: Extra details as per sabanito's comment
So in a simple view/model scenario, if my model had a property called Property1, then my view outputted a Textbox for Property1, when the form is posted via a submit button, the mvc framework will automatically populate a model with Property1 containing the text that was entered into the textbox and pass that model to the Controllers action.
Because I am dealing with a dynamic list of options the user could check, I can't write explicit boolean properties in my model and explicitly create the checkboxes in my view. Given that my list is dynamic, I'm wondering if there are ways to create my model and view so that the mvc framework is able to populate the model correctly when the form is posted.

Here's what I would do:
Are you having any issues generating the checkbox's dynamically?
If not, create a property on your ViewModel that is a:
public List<string> CheckboxResults { get; set; }
When you generate your checkbox's in the view make sure they all share the name = "CheckboxResults". When MVC see's your ViewModel as a parameter on the action method it will automatically bind and put all the "CheckboxResults" results in the List (as well as your other ViewModel properties). Now you have a dynamic List based on which checkbox's your user checked that you can send to your DomainModel or wherever.
Pretty cool stuff. Let me know if you're having issues generating the checkbox's dynamically, that's kind of a seperate issue than model binding to a list.

Use a ViewModel that reflects your view exactly, and map your domain model(s) to the viewmodel.
At first it often seems appropriate to use domain models directly in the view, for no better reason than that they're simple to use. However, as the view gets more complex over time, you end up putting a TON of conditional logic in your view, and end up with spaghetti. To alleviate this, we typically create a ViewModel that correlates 1:1 with the view.

Related

How to make a symfony form with ajax added fields and DTO?

In my view, I have a form that'll allow users to build their own car models. I have a field to choose car-parts and another field to add a color for it. For example, a user can choose "tire"=>"yellow". And there's a button to add new entries to the form.
For generating a form in the controller, I have read many articles on not to bind the entity directly to the form, instead use a DTO (data transfer object) to take care of the validation on the $request first. After a success validation may then have the DTO data pass to the entities.
On submit, my form is going to pass field names like "model_name", "part01", "color01", "part02", "color02" to the controller. From the symfony documentation it shows you how to make it works with the use of the "allow_add" option in the form builder. But here's the problem, that was based on the assumption that you're binding your form with the entities, but how about DTO? How do I put all those data into a DTO and tie it to the form and still able to do the validation?

MVC ViewModel State Dropdown

I am new to MVC and View Models, and trying to wrap my thoughts on how it all works and ties together. I am trying to populate a State dropdown in an Address table. I have a States table with StateAbbr and StateName. What I would like to do is display StateName and save StateAbbr in the Address table. I have been working in the Address Create view. I have tried a number of ways and nothing seems to work so I thought I would just ask the question. My main way of doing it was through Ajax however it would display the StateName but save a Null and was told not to do it this way. Then thought to do it through a ViewModel which I have set up with IEnumerable however I am not sure how to implement it from there.

Html.ValidationMessageFor( MyKey ) without being tiedto a model's attribute?

My model does not really represent what my form is posting. Example my Orgs Model which holds orgs helps me generate a treeview the users selects several nodes of the orgs tree and submits a form. The form posts an array[] or org ids.
(maybe i'm doing this all wrong, please let me know tried binding to models and that was confusing when dealing with trees grids etc and using partial views and ajax returning partial views and editorfor's etc.. the default model binding was useless)
anyways back to my point, since I want to validate if any orgs get selected:
if (SelectedOrgs == null) //array[]
{
ModelState.AddModelError("OrgsNotSelected",IValidationErrors.OrgsNotSelected);
}
my question is how do i retrieve this random key that i just made up from my view? my model and even my viewmodel do not have an array for the selection this is just the result of the post.
I'm not sure what to do in the view to get the value for "OrgsNotSelected".
Thank you!
Bilal
If you were doing normal submit actions to your controller, you would need to use the ValidationSummary to display errors that are not attached to a specific property.
As you are using Ajax, you would be better off returning a json result from your controller and you can define this so that it includes your errors in a format you can use in the success function to display your messages.

Mvc How safe is viewbag?

My website is built around tabs. I have one single page with multiple partial views that display each tab.
The problem im facing now is I want to loop through files that the user has uploaded and display them in one of my partial views. This requires me to send the file list as a paramater in my action like this:
//Uploadedfiles is a function that adds the files to a list.
var files = UploadedFiles();
return View(files);
Because im only using one view to display all my partial views, i get:
The model item passed into the dictionary is of type 'Microsoft.WindowsAzure.Storage.Core.Util.CommonUtility+d__0`1[Delamapp.CloudStorageServices.UploadEntity]', but this dictionary requires a model item of type 'Delamapp.Models.LoginFolder'.
This means im required to not send a model item to my index view. Now, the only thing i can think off is adding my file list to viewbag and then display them on my view. BUT.. The files require high security. How safe is viewbag? Can you for example store sensitive login information in there? Can you think off some other way to accomplish this?
Thank you in advance
You can pass a model item to your view, but the model item you are passing doesn't match the type of model that your view uses (that's what the error message says).
So you need to do one of the following:
Modify your view to accept the model type that you are passing to it
Put the data you want to pass into the model type that your view is expecting
Create a new model type for both your data and for the view, and use that
In terms of security, I don't think using a view bag versus model binding really enters into the question of security. Both are just ways of passing data in between the controller and the view, and that all takes place within the ASP.NET process (perhaps you have ViewBag confused with Web Forms' ViewState?).

Issue with Html.EditorFor on MVC3

I have a view with a form that's is typed to a viewmodel called AddEditItemVM. This viewmodel has the following property:
public List<Category> Categories{get;set;}
What im trying is two things:
Render a checkbox foreach Category in the generic category list of my viewmodel.
Make that when the form is posted receive, in my controller action, the property Categories instantiated (into the instance of AddEditItemVM)
About the first point, i would like to use any helper (if exists) that renders a group of checkboxes using lambda expressions like (m=>m.Categories), instead to render the checkbox with a foreach into the view.
About the second point, i read that there is one feature in MVC called Custom Model Binders. These get values from ValueProviders (querystring, cookies, or Form values) and creates the necessary instances passing it to specific action called after a form was posted. Should i create one custom model binder in order to receive my property Categories instantiated?
This might work
CheckboxList in MVC3.0

Resources