【问题标题】:How to validate ViewModels derived from an abstract class?如何验证从抽象类派生的 ViewModel?
【发布时间】:2011-07-28 13:01:23
【问题描述】:

我有以下 EditorTemplate

@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>

对应于这个ViewModel

public class FileInfo
{
    [Display(Name = "Directory")]
    [Required(ErrorMessage="Please specify the base directory where the file is located")]
    public string Directory { get; set; }
    [Display(Name = "File Name")]
    [Required(ErrorMessage = "Please specify the name of the file (Either a templated filename or the actual filename).")]
    public string Filename { get; set; }

}

我想要做的是重用上面的 EditorTemplate,但根据使用 FileInfo 类的上下文自定义 ErrorMessage。我可以有一个标准文件名,例如 abc.txt 或“模板化”文件名例如abc_DATE.txt 其中DATE 将替换为用户指定的日期。在每种情况下,我都想要一个适当的错误消息。本质上,唯一的区别应该是注释。(我认为这是关键,但不知道如何解决这个问题,因此我的方法很复杂!)

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

 `@model ESG.Web.Models.BaseFileInfo`  

并像使用它一样使用它

@Html.EditorFor(model => model.VolalityFile, "FileInfoEditorTemplate")` 

其中model.VolalityFileTemplatedFileInfo。这些值正确显示在编辑页面上,但是,当字段未正确填写时,没有客户端验证。我最初的猜测是,这与抽象类定义有关(字段上没有任何注释)。

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

这是我能想到的解决我的要求的唯一方法,因此问题 - 如何验证从抽象类派生的 ViewModel?但是,如果有其他更可行的方法来实现这一点,请告知。

【问题讨论】:

    标签: asp.net-mvc-3 validation viewmodel


    【解决方案1】:

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

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

    然后我就这样添加了 ModelErrors:

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

    这可能有点额外的工作和矫枉过正,但它对我有用。

    【讨论】:

    • 你说得对 - 这有点矫枉过正 - 不过谢谢你的建议。
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2020-09-01
    • 2012-09-25
    相关资源
    最近更新 更多