簡體   English   中英

在ASP.NET MVC中處理按鈕單擊的正確方法?

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

我正在制作一個網頁( http://example.com/calculation/ )。 該站點將進行簡單的計算。 該頁面將以文本框(asp:TextBox)的形式向用戶顯示兩個輸入字段。 我想知道如何處理單擊“ Calc”按鈕(asp:Button)?

由於我使用的是MVC模板,是否可以在頁面上使用控制器? 我應該如何組織我的代碼?

我想獲取兩個文本框中的用戶輸入,並在“結果”標簽中輸出值。

最簡單的清除方法是提供Model類,Controller和View。 請看下面的例子:

該模型:

public class CalculatorModel {
    public int Result { get; set; }
    public int FirstOperand { get; set; }
    public int SecondOperand { get; set; }
}

控制器:

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);
    }
}

風景:

<%@ 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>
    <% } %>

我的建議是遵循有關ASP.NET MVC的一些教程。 您可以在Google上找到很多。 ASP.NET MVC網站是一個不錯的起點。

希望能幫助到你!

我相信您的問題是基於對MVC設計模式新手的普遍誤解。 在MVC設計模式中,如何組織模型,視圖和控制器是優先考慮的問題。

就是說,像ASP.NET MVC這樣的Web框架建議某些組織,因為它們傾向於通過站點的URL公開模式實現。 為了進行開箱即用的說明,ASP.NET MVC將為“計算”控制器的add操作創建此路由http://example.com/calculation/add 作為開發人員,您可以通過創建自定義路由來覆蓋此行為,這意味着您應該以對您來說合乎邏輯的方式來組織模型,視圖和控制器。

由於按照定義,您的站點只是在進行簡單的計算,因此我建議創建一個具有多種操作的單個控制器:加,減,除等。Lorenzo提供了如何開始其答案的基礎

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM