Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to handle button clicks in asp.net mvc?

Tags:

c#

asp.net-mvc

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.

like image 200
Jason94 Avatar asked Oct 23 '10 21:10

Jason94


People also ask

How can call POST action method on button click in MVC?

click(function () { //On click of your button var property1 = $('#property1Id'). val(); //Get the values from the page you want to post var property2 = $('#property2Id').


1 Answers

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!

like image 125
Lorenzo Avatar answered Nov 15 '22 06:11

Lorenzo