Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 262
Bardicer Avatar asked Mar 25 '26 22:03

Bardicer


1 Answers

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)
like image 94
LaoR Avatar answered Mar 28 '26 15:03

LaoR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!