Niner
Niner

Reputation: 2205

asp.net mvc dynamic validation depending on action

I have a view model like so:

public class AccountView {
  public int AccountId { get; set; }
  [Required]
  public string AccountName { get; set; }
}

But I would like the AccountName field to be required only if the action is "Edit", but not "Create". How is this accomplished in asp.net mvc3?

thanks.

Upvotes: 0

Views: 241

Answers (2)

s0nica
s0nica

Reputation: 1307

Or you could simply have two different ViewModels: one for the Edit action and one for the Create action. I don't think it's a bad practice even if you duplicate code (not all obviously), as a ViewModel should be tied to the View it's modeling.

Upvotes: 1

user480184
user480184

Reputation:

You can implement a custom validator. Once inside the Validate method you will have access to properties like, (((System.Web.Mvc.ModelValidator)(this))).ControllerContext.Controller where you can look into the ContollerContext, ViewData, etc. You also have access to properties like

  • (((System.Web.Mvc.ModelValidator)(this))).ControllerContext.RequestContext
  • (((System.Web.Mvc.ModelValidator)(this))).ControllerContext.HttpContext
  • (((System.Web.Mvc.ModelValidator)(this))).ControllerContext.RouteData

Upvotes: 0

Related Questions