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

Shi*_*ror 5 c# validation asp.net-mvc asp.net-mvc-5

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

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

我删除了[Required],但我仍然收到此验证消息,阻止我提交.

在视图中我有这些线:

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

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

QuoteQuantity字段是必需的.

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

[DefaultValue(1)]
public int QuoteQuantity { get; set; }
Run Code Online (Sandbox Code Playgroud)

知道为什么会这样吗?

Geo*_*mes 7

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

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

  • QuoteQuantityint 设置为int?(Nullable int)

要么

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

示例:

第一个建议:

public int? QuoteQuantity { get; set; }
Run Code Online (Sandbox Code Playgroud)

第二个建议:(返回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
Run Code Online (Sandbox Code Playgroud)

我会建议第一个选项,并确保你null检查你在哪里使用QuoteQuantity:)

希望这可以帮助!

编辑:

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

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

视图:

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

  • 给它一个id+ name的像quoteQty

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

控制器:

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

  • 之前(ModelState.IsValid)检查,尝试解析quoteQty为一个int; 如果没有,请添加一个带有消息的ModelErrorforquoteQty

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

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

像这样:

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
}
Run Code Online (Sandbox Code Playgroud)

只需使用原始属性

public int QuoteQuantity { get; set; }
Run Code Online (Sandbox Code Playgroud)

在你的模型中.一个int的默认值将是0,如果你从来没有设置.如果TryParse失败,它的值设置为0,太