I have 2 methods : Add and Subtract. I want that when clicked Add button, the 3rd textbox displays the result of A + B; clicked “Subtract” button, the 3rd textbox displays the result of A – B.
I thought it should be a simple thing to do (because it can be done within a few lines of code in ASP.NET WebForm Application). But after trying many times and asked a few of friends, I still cannot find the solution…
@using (Html.BeginForm("Add", "MyMVC"))
{
<ol>
<li>
@Html.TextAreaFor(m => m.A)
</li>
<li><span>+ </span></li>
<li>
@Html.TextAreaFor(m => m.B)
</li>
<li><span>= </span></li>
<li>
@Html.TextAreaFor(m => m.C)
</li>
</ol>
@{
Html.RenderAction("Calculate", "MyMVC");
}
@{
Html.RenderAction("Subtract", "MyMVC");
}
}
The RenderAction tags aren’t needed. The BeginForm extension also needs to render a form element that posts to itself.
Change your view to
Notice the name attribute on the submit inputs, this will enable the default model binder to bind to a property called Calculate.
For you View model use something similar to
Then in the controller have actions similar to:
When the form is submitted via the click events on the submit inputs the value of the button will be auto-magically bound to the Calculate property of the SumModel.
Then when the method RunCalculation is called it uses the property to work out which operation to run against the values A and B