简体   繁体   English

在ASP.Net中提交表单时,十进制值的文本框为null?

[英]Textbox for Decimal value null when submitting form in ASP.Net?

Textbox value when submitting the form is null in the controller. 提交表单时的文本框值在控制器中为空。 Simplified structure of what I have is below: 我所拥有的简化结构如下:

MODEL 模型

public class MyObject
{
    public decimal? DecimalProperty { get; set; }
}

VIEW 视图

@model List<MyObject>

@for(var i = 0; i < Model.Count; i++) 
{
   using (Html.BeginForm("UpdateObject", "MyController", FormMethod.Post))
   {
      @Html.Textbox(String.Format("Model[{0}].DecimalProperty", i), Model[i].DecimalProperty)
      <input type="submit" value="Update"/>
   }
}

CONTROLLER CONTROLLER

public ActionResult UpdateObject(MyObject myObject)
{
   // Do Stuff...
}

If I put a breakpoint in the controller method, then check the property values of myObject, the DecimalProperty is null. 如果我在控制器方法中放置一个断点,然后检查myObject的属性值,则DecimalProperty为null。 There are other properties on the actual object I'm using and those come across alright, but for some reason this property isn't. 我正在使用的实际对象还有其他属性,但是由于某种原因,这个属性不是。 I haven't found anything that suggests that decimals must be handled differently than a DateTime or string. 我没有发现任何暗示小数必须以不同于DateTime或字符串的方式处理的内容。 I have also tried writing out the html for the input by hand: 我也试过用手写出输入的html:

 <input type="text" name="@(String.Format("Model[{0}].DecimalProperty", i))" value="@Model[i].DecimalProperty" />

I have set the name and the id attributes of the textbox just to be on the safe side. 我已经设置了文本框的名称id属性,只是为了安全起见。 Any ideas as to why my textbox value is null when I submit the form? 提交表单时,为什么我的文本框值为null的任何想法?

Setting the [HttpPost] attribute does not help. 设置[HttpPost]属性没有帮助。

The problem is in your action signature. 问题出在你的行动签名中。 You should change it to accept whole list of models, or change Html.TextBox's Name attribute equal to property name of MyObject, cause default MVC binder cannot map it correctly. 您应该将其更改为接受整个模型列表,或将Html.TextBox的Name属性更改为等于MyObject的属性名,导致默认MVC绑定器无法正确映射它。

So, first option: 所以,第一个选项:

public ActionResult UpdateObject(List<MyObject> myObject)
{
   // Do Stuff...
}

Second option: 第二种选择:

@Html.Textbox("DecimalProperty", Model[i].DecimalProperty)

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

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