I'm making a webpage (http://example.com/calculation/
). This site will do simple calculations. The page will present the user with two input fields in the form of text boxes (asp:TextBox). I'm wondering how do I go about handling clicking on the "Calc" button (asp:Button)?
Do I use the controller for the page since I'm using MVC template? How should I organize my code?
I want to fetch the users input in the two text boxes and output the value in a "result" label.
click(function () { //On click of your button var property1 = $('#property1Id'). val(); //Get the values from the page you want to post var property2 = $('#property2Id').
The simplest clean way provides a Model class, a Controller and a View. Please look at the following example:
The Model:
public class CalculatorModel {
public int Result { get; set; }
public int FirstOperand { get; set; }
public int SecondOperand { get; set; }
}
The Controller:
public class CalculatorController : Controller {
[HttpGet]
public ActionResult Sum() {
CalculatorModel model = new CalculatorModel();
//Return the result
return View(model);
}
[HttpPost]
public ActionResult Sum( CalculatorModel model ) {
model.Result = model.FirstOperand + model.SecondOperand;
//Return the result
return View(model);
}
}
The View:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CalculatorModel>" %>
<% using ( Html.BeginForm("Sum", "Calculator", FormMethod.Post, new { id = "calcForm" }) ) { %>
<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>
</table>
<div style="text-align:right;">
<input type="submit" id="btnSum" value="Sum values" />
</div>
<% } %>
My advice is to follow some tutorial on ASP.NET MVC. You can find many with google. The ASP.NET MVC web site is a good place to start.
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With