繁体   English   中英

删除[必需]属性MVC 5后,“必需”验证消息仍然存在

[英]“Required” validation message remains after removal of [Required] attribute MVC 5

我的一个视图模型的属性中有[Required]属性:

[DefaultValue(1)]
[Required(ErrorMessage = "* Required")] // this has now been removed
public int QuoteQuantity { get; set; }

我删除了[Required] ,但我仍然收到此验证消息,导致我无法提交。

在视图中我有这些线:

@Html.EditorFor(model => model.QuoteQuantity, new { htmlAttributes = new { @class = "form-control", value = "1" } })
@Html.ValidationMessageFor(model => model.QuoteQuantity, "", new { @class = "text-danger" })

当我将其留空并提交时,我得到此验证错误:

QuoteQuantity字段是必需的。

我应该提一下,我已经重复构建了解决方案,关闭并重新打开了VS,即使当前代码是这样,我仍然不断收到此验证错误:

[DefaultValue(1)]
public int QuoteQuantity { get; set; }

知道为什么会这样吗?

这是因为你的QuoteQuantity是一个int ,它当前不是Nullable ,所以当你试图验证时,该字段不能为空,因为它不允许null

解决这个问题的两种方法:

  • QuoteQuantity int设置为int? Nullable int

要么

  • 使用不同的属性接受该值作为一个string ,并在getQuoteQuantity ,使用int.TryParse看是否字符串可以转换为int 您需要进行某种检查,但要查看它是否在您的最小/最大范围内 - 如果您有

示例

第一个建议:

public int? QuoteQuantity { get; set; }

第二个建议:(返回0 ,如果字符串为空/ null或不是有效的int

public int QuoteQuantity
{
    get 
    {
        int qty = 0;
        if (!string.IsNullOrWhiteSpace(QuoteQuantityAsString))
        {
            int.TryParse(QuoteQuantityAsString, out qty);
        }
        return qty;
    }
}

public string QuoteQuantityAsString { get; set; }
// You will then need to use the
// QuoteQuantityAsString property in your View, instead

我会建议第一个选项,并确保你在你使用QuoteQuantity地方进行null检查:)

希望这可以帮助!

编辑:

在提供各种选择的公平性中,我只是想到了另一种方式(可能比建议2更好)。 无论哪种方式,我认为建议1仍然是最好的方式。

仅当用户在视图中的“报价数量”字符串输入输入内容时才返回验证:

视图:

  • 在视图中,添加一个文本输入,允许用户输入数量(或不是,可能是这种情况)并使用它来代替当前的QuoteQuantity元素

  • 给它一个id + quoteQty name就像quoteQty

  • 像之前一样添加ValidationFor,但是将quoteQty名称作为第一个参数

控制器:

  • 在你的控制器POST方法中,接受另一个string quoteQty参数(以便它映射到与视图中的name相同)。 这将从您的HttpPost中填充

  • (ModelState.IsValid)检查之前 ,尝试将quoteQty解析为int ; 如果没有, ModelErrorquoteQty添加quoteQty ,并附带消息

  • 然后,您的模型将返回验证错误并根据需要显示在页面上。

  • 缺点是,这无法在客户端验证,因此服务器必须返回错误

像这样:

public ActionResult SendQuote(Model yourmodel,
                              string quoteQty)
{
    if (!string.IsNullOrWhiteSpace(quoteQty))
    {
        if (!int.TryParse(quoteQty, out yourmodel.QuoteQuantity))
        {
            // If the TryParse fails and returns false
            // Add a model error. Element name, then message.
            ModelState.AddModelError("quoteQty",
                                     "Whoops!");
        }
    }
    ...
    // Then do your ModelState.IsValid check and other stuffs
}

只需使用原始属性

public int QuoteQuantity { get; set; }

在你的模型中。 如果你从未设置过, int的默认值将为0 如果TryParse失败,它也将值设置为0

暂无
暂无

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

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