The following code works fine when I enter a number (e.g., 123456) without commas: the number is sent to the Save
action of the controller and 123,456
is displayed in the textbox.
However, when when I click Save
again, and try to enter the number 123,456
with the comma, the Save
action only receives a zero in the model parameter and a zero is then displayed in the textbox.
What am I doing wrong?
Here is the model class:
public class FormatTextBoxFor
{
public double MyDouble { get; set; }
}
Here is the controller:
public class FormatTextBoxForController : Controller
{
public ActionResult Index()
{
FormatTextBoxFor model = new FormatTextBoxFor();
return View(model);
}
[HttpPost]
public ActionResult Save(FormatTextBoxFor model)
{
return View("Index", model);
}
}
And the view:
@using (Html.BeginForm("Save", "FormatTextBoxFor", FormMethod.Post))
{
<p>@Html.TextBoxFor(x => x.MyDouble, string.Format("{0:n0}", Model.MyDouble) )</p>
<input type="submit" name="submit" value="Save" id="submit" />
}
This happens because on the server 123,456 is treated as text and not a number as you defined it in your model. On the server any value sent will will be mapped to the property of you model and parsed using default parser. You have to reformat the value before sending it to the server.