I have a HTML number input on my page that accepts an integer value. The code is as follows:
@Html.TextBox("Answer[" + i + "].Score", null, new { @class = "form-control", type = "number", value="0", id = "Answer[" + i + "]_Score" })
In my model I have defaulted all the Score
properties to 0 but it still didn't render with a 0 in the view. I then used value="0"
directly on the input but it still doesn't render the 0.
It renders like:
<input class="form-control" id="Answer[0]_Score" name="Answer[0].Score" type="number" value="">
This is only a problem when I go to save the form, a null value is sent to the controller when score isn't nullable so the form doesn't submit.
Is there any way to get that 0 to be the default instead of a blank value?
Value = "0"
not
value="0"
value
is a keyword used in setters. for example.
private int num;
public virtual int Number
{
get { return num; }
set { num = value; }
}
As you need to set the value of "num" (in this case Answer_++) explicitly in the code behind when you create the object - the value is not set, so it is empty.
So Value
is not overwritten by the value of the setter.
Also always have error handling and null checks when passing data through controllers.