使用MVC的计算器
本文关键字:计算器 MVC 使用 | 更新日期: 2023-09-27 18:21:09
我是MVC和C#的新手,我必须制作一个带有数字按钮的计算器。如何将视图中的按钮值传递给控制器?有我可以使用的源代码吗?
这是视图中的按钮表
<form name="Cal">
<table border=1>
<tr>
<td width="65%" align="center">
<input type="text" name="Input" size="20" onchange="FixValue()">
<br>
</td>
</tr>
<tr>
<td width="65%" align="center">
<input type="button" name="one" value="1" onclick="f1(this.value)">
<input type="button" name="two" value="2" onclick="f1(this.value)">
<input type="button" name="three" value="3" onclick="f1(this.value)">
<input type="button" name="plus" value="+" onclick="Operate(this.value)">
<br>
<input type="button" name="four" value="4" onclick="f1(this.value)">
<input type="button" name="five" value="5" onclick="f1(this.value)">
<input type="button" name="six" value="6" onclick="f1(this.value)">
<input type="button" name="minus" value="-" onclick="Operate(this.value)">
<br>
<input type="button" name="seven" value="7" onclick="f1(this.value)">
<input type="button" name="eight" value="8" onclick="f1(this.value)">
<input type="button" name="nine" value="9" onclick="f1(this.value)">
<input type="button" name="multiply" value="*" onclick="Operate(this.value)">
<br>
<input type="button" name="Clr" value="c" onclick="AllClear()">
<input type="button" name="zero" value="0" onclick="f1(this.value)">
<input type="button" name="answerswer" value="=" onclick="Calculate()">
<input type="button" name="divide" value="/" onclick="Operate(this.value)">
<br>
</td>
</tr>
</table>
</form>
如果你不想使用JavaScript,你可以在Url.Action
:中使用匿名对象直接调用你的操作
<input type="button" name="one" value="1" onclick="location.href='@Url.Action("YourAction", "YourController", new { value = 1 })'">
这是控制器的C#代码:
public ActionResult YourAction(int value)
{
//your code
}
如果您只是想将值传递给控制器,那么可能需要使用jQuery的$.get
或$.post
。
例如,你的f1可能看起来像:
function f1(object) {
$.get('/Calculator/DoButtonPostBack?Button=' + $(object).val());
}
你的控制器可能看起来像:
public class CalculatorController : Controller
{
public ActionResult DoButtonPostBack(string button)
{
//do sometihng
}
}
不过,您可能只想在大多数情况下使用JavaScript编写计算器。