MVC: Client validation on list of object (At least one) - asp.net-mvc

I want to implement client validation on a list of objects. I want to make sure that the list has at least one object, so I used custom validation as described here and made it client validable. This works well when the list is of simple datatype like an int.
That is
public List<int> var{get; set;}
With this I can include a Listboxfor in my view and when the form containing the list is submitted, client validation kicks in. However I now have a list of objects
public List<MyClass> var{get; set;}
Items are added to this list dynamically. I can therefore not have a ListBoxFor in my View. How can i display the list in my View so that that client validation picks it up?

Related

ASP.NET MVC: Client validation for complex patial views

I have this viewmodel:
public class Letter
{
public strng Name{get;set;}
[UIHint("UserSelector")]
[Required]
public List<int> Users{get;set;}
}
For rendering Letter viewmodel I use Html.EditorForModel(). EditorTemplate "UserSelector" is complex view and looks like this:
Before submitting the form I manually generate hidden field controls for selected users and it's obviously RequiredAttribute doesn't work for Users property. What's "true" way to force UserSelector view to "understand" RequiredAttribute?
you could have a another string with empty value at first, and then use it in a hidden input, then make it required. Every time client add a user from left to right, update that hidden input value like 'Usera,Userb ....'. So when client tries to submit the form, this hidden input must have value.

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

mvc modelbinding

I have an Edit action/view for my User object, but only want a few fields to be editable.
I've set up the view to bind to the User object, and am using Html.EditorFor() for the few fields that I want to be editable.
I noticed in my User object on Post:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditUser(Mynamespace.User user)
{ }
that only the fields that I provided .EditorFor() controls for actually have any data.
I tried using Html.Hidden(Model.ID) for one of the fields that i didn't want to be editable, but it is null in the new User object created from model binding.
So, my question- How do I bind where only a couple of the fields should be editable?
Thanks!
It sounds like you probably want to start thinking about using a View Model that is specific to the form/input that you're dealing with. But in the short term, ....
You could bind to a FormCollection parameter instead and copy the values manually, OR...
you can use the TryUpdateModel method to populate this existing user object with the new data.
Here's the documentation for TryUpdateModel:
http://msdn.microsoft.com/en-us/library/dd470756.aspx
It's still possible for malicious users to send phony form-values that map to real properties on your model, so to protect against this (like an employee changing his salary property with a simple form hack) you can introduce an interface that contains the white list properties that you allow.
Here's an example:
public interface IUserEditableFields
{
string Username {get;set;}
string Email {get;set;}
}
//... in the controller action
if(TryUpdateModel<IUserEditableFields>(user)) {
//validation passed
//only Username and Email were editable
}
This is a good resource on how to do this:
http://css.dzone.com/news/aspnet-mvc-think-before-you-bi
Are you using the strongly-type helper for the hidden field or is it exactly like you've typed. If you've got it exactly as typed, then the name of the hidden field is the value of the id, not the name of the property on the model (ID). You might want to change it to:
<%= Html.Hidden( "ID" ) %>
or (if using strongly-typed helpers)
<%= Html.HiddenFor( m => m.ID ) %>
Ben's answer is largely correct, in that a ViewModel might be more appropriate, and short of that, TryUpdateModel can be used. However, I add that in that case, rather than requiring the domain object to implement a new interface, you use the overload TryUpdateModel<T>(T, string[]), which allows you to whitelist the updateable properties in a string array by name.

Using a dynamic list of checkboxes in a view, how to create the model

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.

asp.net-mvc - how do i create a view to show all unapproved users and allow them to be approved

i have this code in my membership service class (taken from the asp.net-mvc sample app)
public MembershipUserCollection GetUnapprovedUsers()
{
MembershipUserCollection users = Membership.GetAllUsers();
MembershipUserCollection unapprovedUsers = new MembershipUserCollection();
foreach (MembershipUser u in users)
{
if (!u.IsApproved)
{
unapprovedUsers.Add(u);
}
}
return unapprovedUsers;
}
i now need a view to show this list of information and allow someone to approve them which will go back to the controller and set the IsApproved property to true.
Create a view which will generate a form containing label and checkbox for each member of the collection. You need to be able to get from the id of the checkbox to the user.
In the HTTP.POST Action method, iterate through the submitted fields looking for set checkboxes, when you find one set the corresponding user to approved.
Obviously the form can display arbitrary details for each user.
To use the inbuilt control helpers takes a bit more effort because you don't have a fixed size model to work with. To achieve something similar I:
Used a non-strongly typed view
populated ViewData["ids"] with IEnumerable<IdType> (which the view would loop over)
For each entry populated ViewData["field" + id] for each field I was displaying in the entity
In the view looped over the ids using ViewData["ids"] to call the HTML helpers with the id of the field.
(That was V1, in V2 I used model state so I could use the inbuilt validation error display support, but that doesn't really apply if you just want to select users.)
The POST processing was similar, repopulating the id list from the database and the looking up in the passed FormCollection.

Resources