需要创建一个请求三个整数并使用HTTPPost打印出总和的C#类。
本质上,我需要创建一个具有用户输入三个整数的Web应用程序,然后打印出它们的总和。我需要在一个类中创建该程序并使用HTTP Post协议进行打印。需要创建一个请求三个整数并使用HTTPPost打印出总和的C#类。
下面是我首先制作的控制台应用程序,以及我在标准MVC(减去模型)中做这件事的尝试。我特别的问题是,我对HTML表单以外的Post方法的使用经验很少,试图查找关于它的信息并没有帮助。
1日尝试 - 控制台应用程序
int num1;
int num2;
int num3;
int sum;
Console.Write("First number: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Third number: ");
num3 = Convert.ToInt32(Console.ReadLine());
sum = num1 + num2 + num3;
Console.WriteLine("Sum: {0}", sum);
Console.ReadLine();
第二尝试 - 控制器
public class HomeController : Controller
{
// GET: Home
// Integers initiated in the index parameters.
public ActionResult Index(int firstInt = -0, int secondInt = -0, int thirdInt = -0)
{
// Calculates sum of the three integers, and then sends result to the View.
int sum = firstInt + secondInt + thirdInt;
ViewBag.result = sum;
return View();
}
}
第二尝试 - 指数
@{
ViewBag.Title = "Index";
}
<form action="" method="post">
<table>
<tr><td>Enter the 1st Number: <input id="firstInt" name="firstInt" type="text" value="0" /></td></tr>
<tr><td>Enter the 2nd Number: <input id="secondInt" name="secondInt" type="text" value="0" /></td></tr>
<tr><td>Enter the 3rd Number: <input id="thirdInt" name="thirdInt" type="text" value="0" /></td></tr>
<tr>
<td><input id="Submit" type="submit" value="submit" /><input id="Reset" type="reset" value="reset" /></td>
</tr>
<tr>
<td>
Sum =
@if (ViewBag.result != 0)
{
@ViewBag.result
}
</td>
</tr>
</table>
需要两个指数()方法,我相信。一个不接受参数,只返回View()来显示输入表单,第二个接受[HttpPost]属性,并且大部分是你写的。
这是使用ASP.NET MVC和Razor页面,路由引擎将确保为POST请求选择了[HttpPost]方法。
我需要写什么不同使用Razor以使表单与该方法进行通信,并使ASP能够协调两个相同名称的控制器? –
我已经解释过了。你必须在同一个控制器类中编写两个Index()方法。其中之一将有[HttpPost]属性,所以你最终得到例如。 空隙指数() { } [HttpPost] 空隙指数(一些-参数) { } ASP.NET MVC将看到一个传入请求,这将是或者是GET或POST HTTP动词[出于本示例的目的],并根据它所看到的HTTP动词将请求指向上述任一控制器方法。 – Kevmeister68
“使用HTTP Post协议打印结果”是什么意思?您是否希望控制台应用程序在HTTP响应中打印结果? – Kzrystof
您必须将控制器操作添加到表单。请参阅https://stackoverflow.com/questions/15190929/how-to-link-html5-form-action-to-controller-actionresult-method-in-asp-net-mvc-4 – Greg