0

Say I have a class called Test and I have a Create and Edit view. Say this class is incredibly simple

public class Test
{
    [Required]
    public string str { get; set; }
}

Is it possible to remove the required attribute when a user is editing this object?

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
CBC_NS
  • 1,961
  • 4
  • 27
  • 47

1 Answers1

5

ViewModels are there for this. One for Create and one for Edit.

You should use a ViewModel for this, as you need View Specific Models here :

public class CreateTestViewModel
{
    [Required]
    public string str { get; set; }
}

and:

public class EditTestViewModel
{
    public string str { get; set; }
}

You might want to read about What is ViewModel in MVC and How to use ViewModel in MVC

Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • If EditTestViewModel Inherited from CreateTestViewModel, could you override str without it being required, or is the proper solution here to just separate the classes entirely? – CBC_NS Apr 07 '17 at 14:55
  • they should be separate, no inheritance :) – Ehsan Sajjad Apr 07 '17 at 14:56