When using the following code MyValue is lost when the view model is sent to the controller.
@Html.TextBoxFor(x => Model.MyValue, new { @Value = String.Format("{0:N0}", Model.MyValue) })
When I remove the String.Format() portion the value is passed correctly. Fyi, MyValue is a double.
How can I pass MyValue while retaining the formatting?
I've tried using a separate HiddenFor but this did not work. Also, I suspect if MyValue where a string instead of a double, the value would be passed. However, for now I'd rather keep it a double unless there is no easier way.
Edit
Unfortunately I'm still having the same problem. Here are some more details of the situation.
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 Text Box. 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 displayed in the Text Box
What am I doing wrong?
Here is the Model:
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" />
}
.TextBoxForwhere you can give the format-string - you should use this and I never had any problems using this msdn.microsoft.com/en-us/library/hh833694(v=vs.118).aspx