无法发送格式的TextBoxFor值回控制器 [英] Having trouble sending formatted TextBoxFor Value back to the controller
问题描述
以下code,当我输入一个数字(如123456),而逗号工作正常:该号码发送到控制器和的保存
行动 123456
显示在文本框中。
然而,当我点击保存
一遍,并尝试输入号码 123456
与逗号,则保存
的行动只是在模型参数接收一个零和零,然后在文本框中显示。
我是什么做错了吗?
下面是模型类:
公共类FormatTextBoxFor
{
公共双MyDouble {搞定;组; }
}
下面是控制器:
公共类FormatTextBoxForController:控制器
{
公众的ActionResult指数()
{
FormatTextBoxFor模式=新FormatTextBoxFor();
返回查看(模型);
} [HttpPost]
公众的ActionResult保存(FormatTextBoxFor模型)
{
返回查看(「指数」,型号);
}
}
和视图:
@using(Html.BeginForm(保存,FormatTextBoxFor,FormMethod.Post))
{
&所述p为H.; @ Html.TextBoxFor(X => x.MyDouble,的String.Format({0:N0},Model.MyDouble))≤; / P> <输入类型=提交名称=提交值=保存ID =提交/>
}
这是因为在服务器上的123456正如你在模型中定义它被视为文本,而不是数字。在服务器发送的任何值将被映射到你的模型的属性,并使用默认的解析器解析。你必须把它发送到服务器之前重新格式化的值。
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.
这篇关于无法发送格式的TextBoxFor值回控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!