在asp.net mvc中处理按钮点击的正确方法?

Jas*_*n94 6 c# asp.net-mvc

我正在制作一个网页(http://example.com/calculation/).该网站将进行简单的计算.该页面将以文本框(asp:TextBox)的形式向用户显示两个输入字段.我想知道如何处理点击"Calc"按钮(asp:按钮)?

因为我使用MVC模板,我是否将控制器用于页面?我该如何组织我的代码?

我想在两个文本框中获取用户输入,并在"结果"标签中输出值.

Lor*_*nzo 12

最简单的干净方式提供了Model类,Controller和View.请看下面的例子:

该模型:

public class CalculatorModel {
    public int Result { get; set; }
    public int FirstOperand { get; set; }
    public int SecondOperand { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制者:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

风景:

<%@ 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>
    <% } %>
Run Code Online (Sandbox Code Playgroud)

我的建议是遵循ASP.NET MVC的一些教程.你可以找到很多与谷歌.在ASP.NET MVC的网站是一个良好的开端.

希望能帮助到你!