Asp.net mvc 3 如何验证从抽象类派生的ViewModels?

Asp.net mvc 3 如何验证从抽象类派生的ViewModels?,asp.net-mvc-3,validation,viewmodel,Asp.net Mvc 3,Validation,Viewmodel,我有以下编辑器模板 @model ESG.Web.Models.FileInfo // <-- Changed to BaseFileInfo @{ ViewBag.Title = "FileInfoEditorTemplate"; } <fieldset> <table class="fileInfoEdit"> <tr> <td>Base Directory:</td>

我有以下编辑器模板

@model ESG.Web.Models.FileInfo // <-- Changed to BaseFileInfo
@{
    ViewBag.Title = "FileInfoEditorTemplate";
}
<fieldset>
    <table class="fileInfoEdit">
        <tr>
            <td>Base Directory:</td>
            <td>@Html.EditorFor(model => model.Directory)</td>
            <td>@Html.ValidationMessageFor(model => model.Directory)</td>
        </tr>
        <tr>
            <td>Filename:</td>
            <td>@Html.EditorFor(model => model.Filename)</td>
            <td>@Html.ValidationMessageFor(model => model.Filename)</td>
        </tr>
    </table>
</fieldset>
我想做的是重用上面的EditorTemplate,但根据
FileInfo
类所使用的上下文自定义
ErrorMessage
。我可以有一个标准文件名,例如
abc.txt
或一个“模板化”文件名,例如
abc_DATE.txt
,其中
DATE
将替换为用户指定的日期。我希望在每种情况下都有适当的错误消息。本质上,唯一的区别应该是注释。(我认为这是关键,但不确定如何解决这个问题,因此我的方法很复杂!)

我尝试创建一个抽象的基本视图模型,然后派生一个标准文件和模板化的FileInfo类。我将当前EditorTemplate上的声明更改为

 `@model ESG.Web.Models.BaseFileInfo`  
像这样使用它

@Html.EditorFor(model => model.VolalityFile, "FileInfoEditorTemplate")` 
其中,
model.VolalityFile
是一个
TemplatedFileInfo
。值正确显示在编辑页面上,但是,如果字段填写不正确,则不会进行客户端验证。我最初的猜测是,这与抽象类定义有关(字段上没有任何注释)


这是我能想到的解决我的需求的唯一方法,因此问题是——如何验证从抽象类派生的ViewModels?但是,如果有其他更可行的方法来实现这一点,请提供建议。

我遇到过类似的情况,我必须根据另一个属性的值更改消息

我做了整个验证服务器端,没有注释

然后我就这样添加了ModelErrors:

ModelState.AddModelError("YourPropertyName", "The Error Message you want to show.);

这是一项额外的工作,可能有点过分了,但对我来说确实是个好办法。

你说得对-这是过分了-不过谢谢你的建议。
public abstract class BaseFileInfo
{
    public abstract string Directory { get; set; }
    public abstract string Filename { get; set; }
}

// eg of derived class
public class TemplatedFileInfo : BaseFileInfo
{
    [Display(Name = "File Name")]
    [Required(ErrorMessage = "Please specify the name of a templated file eg someFileName_DATE.csv")]
    public override string Filename { get; set; }

    [Display(Name = "Directory")]
    [Required(ErrorMessage="Please specify the base templated directory where the file is located")]
    public override string Directory { get; set; }
}
ModelState.AddModelError("YourPropertyName", "The Error Message you want to show.);