简体   繁体   中英

asp mvc viewmodel validation attribute

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; }
}

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; }
}

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.

虽然Bigfellahull的解决方案是一个更好的方法,但在更新操作中你可以检查ModelError然后如果错误与字段CommonFile有关,那就忽略它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM