ModelState验证未显示哪些字段无效

时间:2017-09-06 15:18:41

标签: asp.net-core-mvc modelstate

我的ModelState验证给了我非常一般的错误消息,我想确切地知道哪些字段是无效的。

Example

正如您可以看到前两个文本框"启动速率< 1分钟"和"启动率1-3分钟"两者都是空的,但模型状态验证消息只说"值''无效"。我想说明哪些字段完全无效。

我在视图中放置了以下行:<div asp-validation-summary="All"></div>

这是我的控制器操作和我的带有必需属性的模型:

[HttpPost]
public async Task<IActionResult> EditSubtitleSetting(EditSubtitleSettingsModel model)
{
    try
    {
        if (ModelState.IsValid)
        {
            await _subtitleSettingService.UpdateSubtitleSetting(model);
            return RedirectToAction("Subtitling");
        }
    } catch (CustomException e)
    {
        foreach (var m in e.Messages)
        {
            ModelState.AddModelError(m.Key, m.Message);
        }
    }
    return View(model);
}


public class EditSubtitleSettingsModel
{
    public string Id { get; set; }
    public string FromLanguage { get; set; }
    public string ToLanguage { get; set; }

    [Required(ErrorMessage = "Startup rate less than one minute is required")]
    public decimal StartupRateLessThanOneMinute { get; set; }

    [Display(Name = "Startup rate between one and three minutes")]
    [Required(ErrorMessage = "Startup rate between one and three minutes is required")]
    public decimal StartupRateBetweenOneAndThreeMinutes { get; set; }

    [Required(ErrorMessage = "Startup rate between three and five minutes is required")]
    public decimal StartupRateBetweenThreeAndFiveMinutes { get; set; }

    [Required(ErrorMessage = "Price per subtitle is required")]
    public decimal PricePerSubtitle { get; set; }

    [Required(ErrorMessage = "Default rate for translators is required")]
    public decimal DefaultRateTranslators { get; set; }
}

如何让验证消息告诉我哪些字段无效?

1 个答案:

答案 0 :(得分:0)

显然,required属性仅适用于nullable decimal。所以我将我的模型改为只有可以为零的小数,现在它正确地显示了验证消息。这是一个非常简单的解决方法。

这就是我的模型现在的样子:

public class EditSubtitleSettingsModel
{
    public string Id { get; set; }
    public string FromLanguage { get; set; }
    public string ToLanguage { get; set; }

    [Required(ErrorMessage = "Startup rate less than one minute is required")]
    public decimal? StartupRateLessThanOneMinute { get; set; }

    [Required(ErrorMessage = "Startup rate between one and three minutes is required")]
    public decimal? StartupRateBetweenOneAndThreeMinutes { get; set; }

    [Required(ErrorMessage = "Startup rate between three and five minutes is required")]
    public decimal? StartupRateBetweenThreeAndFiveMinutes { get; set; }

    [Required(ErrorMessage = "Price per subtitle is required")]
    public decimal? PricePerSubtitle { get; set; }

    [Required(ErrorMessage = "Default rate for translators is required")]
    public decimal? DefaultRateTranslators { get; set; }
}