views:

31

answers:

2

I've got a ViewModel for adding a user with properties: Email, Password, ConfirmPassword with Required attribute on all properties. When editing a user I want the Password and ConfirmPassword properties not to be required.

Is there a way to disable validation for certain properties in different controller actions, or is it just best to create a seperate EditViewModel?

+1  A: 

I like to break it down and make a base model with all the common data and inhierit for each view:

class UserBaseModel
{
    int ID { get; set; }

    [Required]
    string Name { get; set; }       

    [Required]
    string Email { get; set; }               
    // etc...
}

class UserNewModel : UserBaseModel
{
    [Required]
    string Password { get; set; }

    [Required]
    string ConfirmPassword { get; set; }
}

class UserEditModel : UserBaseModel
{
    string Password { get; set; }
    string ConfirmPassword { get; set; }
}

Interested to know if there is a better way as well although this way seems very clean an flexible.

Kelsey
A: 

You could write a custom attribute that can test a condition and either allow an empty field or not allow it.

The below is a simple demo i put together for the guys here. You'll need to modify to suit your purposes/

    using System.ComponentModel.DataAnnotations;

    namespace CustomAttributes

    {

    [System.AttributeUsage(System.AttributeTargets.Property)]

    public class MinimumLength : ValidationAttribute

    {
        public int Length { get; set; }
        public MinimumLength()
        {
        }

        public override bool IsValid(object obj)
        {
            string value = (string)obj;
            if (string.IsNullOrEmpty(value)) return false;
            if (value.Length < this.Length)
                return false;
            else
                return true;
        }
    }
}

Model;

using CustomAttributes;

namespace Models
{
    public class Application
    {
        [MinimumLength(Length=20)]
        public string name { get; set; }
    }
}

Controller

 [AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Application b)
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    if (ModelState.IsValid)
    {
        return RedirectToAction("MyOtherAction");
    }
    return View(b);
}

enter code here
griegs
The problem is that I want the field to be required in one Controller Action but not in another Controller Action, could there be a way for the custom attribute to know which action it is currently in?
adriaanp
Yes there is and you'd need to google it as i can't think of it right now. This may help you. http://stackoverflow.com/questions/1212429/get-controllername-and-actionname-and-populate-the-viewdata-in-master-page
griegs