Reputation: 1158
I am trying to sum two number using a from submit. HttpGet is working properly but on submit of the form I am unable to show it in view ..
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>
}
Initially it's showing 7 as 3 plus 4
but when I changed my value and post it it's not showing the old value ..Have debugged in controller it's showing perfectly but not posting to view properly
Upvotes: 0
Views: 2362
Reputation: 218732
You need to clear the previous result value from model state dictionary. You may use the ModelState.Clear()
method to do that.
[HttpPost]
public ActionResult Sum(CalculatorModel model)
{
ModelState.Clear();
model.Result = model.FirstOperand + model.SecondOperand;
return View(model);
}
Upvotes: 5