c# - MVC 数字输入被视为 null

标签 c# asp.net-mvc

使用一个表单(使用 Html.BeginForm),我有一个类型为 numberinput。当我这样提交时:

input type number

我收到以下错误:

The parameters dictionary contains a null entry for parameter 'AmountOnHand' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Ingredient(Int32, System.String, Int32, System.String)' in 'BrewReport.Web.Controllers.AdminController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

形式(简化)如下:

@using (Html.BeginForm("Ingredient", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="AmountOnHand" type="number" class="form-control" min="0" required="required" />
<input type="submit" class="btn btn-primary btn-lg" value="Save Changes to Ingredient" />
}

Controller 方法如下:

[HttpPost]
public ActionResult CreateIngredient(string ingredientName, decimal amountOnHand, string measurementUnit)
{
    IngredientsData.SaveIngredient(ingredientName, amountOnHand, measurementUnit);
    return RedirectToAction("ManageIngredients");
}

最佳答案

您的输入字段缺少 name 属性,因此当它被发送回服务器时,没有提供任何值并且您的代码中断。

您可以使用以下方法之一解决此问题:

name 属性添加到您的输入字段。

<input id="AmountOnHand" name="AmountOnHand" type="number" class="form-control" min="0" required="required" />

使用 Html Helper 生成您的字段标记

@Html.TextBoxFor(x => x.AmountOnHand, new { @type="number", @class="form-control", min="0", required="required" });

这还将为您添加 name 属性,并具有强类型的额外好处,以防您将来更改属性名称。

关于c# - MVC 数字输入被视为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31174221/

相关文章:

c# - 无法获取 Microsoft Azure 存储帐户设置

c# - SQLiteDataReader,最后一次Read()需10秒

c# - 在 systemd 文件中使用 Environment= 解析 ASP.NET Core 连接字符串

c# - 需要简单的 Twitter API v1.1 示例来使用 jQuery 或 C# ASP.NET 显示时间线

c# - ASP .NET Core MVC 部署到 azure Identity Server 4

c# - ASP.NET MVC ViewModel 和 DropDownList

c# - 当前上下文中不存在名称 'data'

c# - 网络 API : FromBody always null

c# - HTML Agility Pack - 如何在 Head 元素的顶部附加元素?

c# - 在 Telerik MVC AJAX 绑定(bind)属性列上使用自定义日期格式化程序