Having trouble sending formatted TextBoxFor Value

2019-09-09 17:14发布

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

1条回答
我只想做你的唯一
2楼-- · 2019-09-09 18:03

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.

查看更多
登录 后发表回答