简体   繁体   English

asp mvc viewmodel验证属性

[英]asp mvc viewmodel validation attribute

I am using one ViewModel for two actions: create and update. 我正在使用一个ViewModel进行两项操作:创建和更新。 But field 但是场

CommonFile CommonFile

(with required attribute) is situated in Create view. (带有必需属性)位于“创建”视图中。 So ModelState.IsValid is false in update action. 因此更新操作中ModelState.IsValid为false。 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 拥有一个继承UnitViewModel的CreateViewModel

public class CreateViewModel : UnitViewModel 
{
    [Required(ErrorMessage = "Required field")] 
    [FileAttribute(AllowedFileExtensions = new string [] { ".xls", ".xlsx" })]
    public HttpPostedFileBase CommonFile { get; set; }
}

This is an OO question. 这是一个OO问题。 Create a BaseUnitViewModel that has everything but the CommonFile, then derive from it with the CommonFile for your method that needs it. 创建一个BaseUnitViewModel,它包含除CommonFile之外的所有内容,然后使用CommonFile从中派生出需要它的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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