0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.