Reputation: 436
i have 3 input text and one button in my view like this
@using (Html.BeginForm()) {
<input id="Text1" name="txtNum1" type="text" placeholder="num 1" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
<input id="Text2" name="txtNum2" type="text" placeholder="num 2" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
<input id="Text3" name="txtNum3" type="text" readonly="readonly" />
<input id="Submit1" type="submit" value="Sum" />
}
in my controller ,when i click submit button ,i want to sum the 2 input text and put result in the third text , this is my controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(int txtNum1=0,int txtNum2=0, int txtNum3=0)
{
txtNum3= txtNum1+ txtNum2;
return View(txtNum3);
}
when i put numbers in the 1st and 2nd text then click submit it post back but i don't show any result in the 3rd text .
so how can i fix this code?
Upvotes: 0
Views: 2735
Reputation: 62488
You need to create a Model class first of all, in your case it will contains three properties as you have three textboxes and the input will be numbers, so use int
.
Your model class will be :
public class SumModel
{
public int Number1 { get;set;}
public int Number1 {get;set;}
pubilc int Result {get { return Number1 + Number2;}}
}
then in your view you will need to specify which Model
it is fimiliar with of, which means which model this view is binded with :
@model YourNameSpace.Models.SumModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(x=>x.Number1)
@Html.TextBoxFor(x=>x.Number2)
@Html.TextBoxFor(x=>x.Result, new {@readonly = "readonly"})
<input id="Submit1" type="submit" value="Sum" />
}
and in controller action add the parameter of type SumModel
:
[HttpPost]
public ActionResult Index(SumModel model)
{
return View(model);
}
after the model posted the View will be re-rendered with the third textbox with the sum value of two textboxes.
Upvotes: 3