Textbox for null decimal when submitting a form in ASP.Net?

The value of the textbox when submitting the form in the controller is null. A simplified structure of what I have is below:


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



@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"/>



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 it all works out well, but for some reason this property is missing. I haven't found anything that suggests decimals should be handled differently than DateTime or string. I also tried to write html for manual input:

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


I set the name and id attributes of the textbox just to be safe. Any ideas as to why the value of my textbox is null when I submit the form?

Setting the [HttpPost] attribute doesn't help.


source to share

1 answer

The problem is with your action signature. You have to change it to accept the entire list of models, or change the Html.TextBox Name attribute to the name of the MyObject property, because the default MVC binder can't render it correctly.

So the first option:

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


Second option:

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




All Articles