Reputation: 971
I am using one ViewModel for two actions: create and update. But field
CommonFile
(with required attribute) is situated in Create view. So ModelState.IsValid is false in update action. How to use one modelview in this two views?
public class UnitViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Required field")]
[StringLength(256, ErrorMessage = "SomeMessage")]
public string Title { get; set; }
public string Code { get; set; }
[Required(ErrorMessage = "Required field")]
[DateAttribute(ErrorMessage = "Incorrect date format")]
public string MapDeadline { get; set; }
public int InAllCount { get; set; }
public int LoadedCount { get; set; }
[Required(ErrorMessage = "Required field")]
[FileAttribute(AllowedFileExtensions = new string [] { ".xls", ".xlsx" })]
public HttpPostedFileBase CommonFile { get; set; }
}
Upvotes: 1
Views: 2470
Reputation: 332
although Bigfellahull's solution is a much better approach, In update action you can check the ModelError then if the error is related to field CommonFile, just ignore it.
Upvotes: 0
Reputation: 3689
Have a CreateViewModel that inherits UnitViewModel
public class CreateViewModel : UnitViewModel
{
[Required(ErrorMessage = "Required field")]
[FileAttribute(AllowedFileExtensions = new string [] { ".xls", ".xlsx" })]
public HttpPostedFileBase CommonFile { get; set; }
}
Upvotes: 4
Reputation: 34822
This is an OO question. Create a BaseUnitViewModel that has everything but the CommonFile, then derive from it with the CommonFile for your method that needs it.
Upvotes: 0