![](/img/trans.png)
[英]Proper way to handle maneuvering through pages using buttons in 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.