简体   繁体   中英

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

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. 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. I have also tried writing out the html for the input by hand:

 <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. Any ideas as to why my textbox value is null when I submit the form?

Setting the [HttpPost] attribute does not help.

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.

So, first option:

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

Second option:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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