我正在尝试使用from submit来汇总两个数字。 HttpGet工作正常但在提交表单时我无法在视图中显示它。
public class CalculatorController : Controller
{
//
// GET: /Calculator/
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Sum()
{
CalculatorModel model = new CalculatorModel();
model.FirstOperand = 3;
model.SecondOperand = 4;
model.Result = model.FirstOperand + model.SecondOperand;
//Return the result
return View(model);
}
[HttpPost]
public ActionResult Sum(CalculatorModel model)
{
model.Result = model.FirstOperand + model.SecondOperand;
//Return the result
return View(model);
}
}
@model HTMLHelpersDemo.Models.CalculatorModel
@{
ViewBag.Title = "Sum";
}
<h2>Sum</h2>
@using (Html.BeginForm("Sum", "Calculator", FormMethod.Post))
{
<table border="0" cellpadding="3" cellspacing="1" width="100%">
<tr valign="top">
<td>
@Html.LabelFor(model => model.FirstOperand)
@Html.TextBoxFor(model => model.FirstOperand)
</td>
</tr>
<tr valign="top">
<td>
@Html.LabelFor(model => model.SecondOperand)
@Html.TextBoxFor(model => model.SecondOperand)
</td>
</tr>
<tr valign="top">
<td>
@Html.LabelFor(model => model.Result)
@Html.TextBoxFor(model => model.Result)
</td>
</tr>
</table>
<div style="text-align:right;">
<input type="submit" id="btnSum" value="Sum values" />
</div>
}
最初它显示7为3加4
但是当我更改了我的价值并发布它没有显示旧值时..已在控制器中调试它显示完美但未发布以正确查看
答案 0 :(得分:4)
您需要清除模型状态字典中的上一个结果值。您可以使用ModelState.Clear()
方法来执行此操作。
[HttpPost]
public ActionResult Sum(CalculatorModel model)
{
ModelState.Clear();
model.Result = model.FirstOperand + model.SecondOperand;
return View(model);
}