需要创建一个C#类,该类请求三个整数,并使用HTTPPost打印出一个和
本质上,我需要创建一个web应用程序,让用户输入三个整数,然后输出它们的和。我需要在一个类中创建这个程序,并使用HTTPPOST协议打印它 下面是我首先制作的控制台应用程序,以及我在标准MVC(不包括模型)中的尝试。我的特别问题是,我对HTML表单之外的Post方法几乎没有经验,试图查找有关它的信息也没有帮助 第一次尝试-控制台应用程序需要创建一个C#类,该类请求三个整数,并使用HTTPPost打印出一个和,c#,asp.net,class,post,http-post,C#,Asp.net,Class,Post,Http Post,本质上,我需要创建一个web应用程序,让用户输入三个整数,然后输出它们的和。我需要在一个类中创建这个程序,并使用HTTPPOST协议打印它 下面是我首先制作的控制台应用程序,以及我在标准MVC(不包括模型)中的尝试。我的特别问题是,我对HTML表单之外的Post方法几乎没有经验,试图查找有关它的信息也没有帮助 第一次尝试-控制台应用程序 int num1; int num2; int num3; int sum; Console.
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>
@{
ViewBag.Title=“Index”;
}
输入第一个数字:
输入第二个数字:
输入第三个数字:
总和=
@如果(ViewBag.result!=0)
{
@ViewBag.result
}
我认为您需要两个Index()方法。一个不接受任何参数,只返回View()以显示输入表单,第二个被赋予[HttpPost]属性,基本上与您编写的相同
这是使用ASP.NET MVC和Razor页面,路由引擎将确保为POST请求选择[HttpPost]方法。您所说的“使用HTTP POST协议打印结果”是什么意思?是否希望控制台应用程序在HTTP响应中打印结果?必须将控制器操作添加到表单中。看看我需要用Razor写些什么,才能让表单与方法通信,这样ASP就可以协调两个同名的控制器了?我已经解释过了。必须在同一控制器类中编写两个Index()方法。其中一个将具有[HttpPost]属性,因此您最终将使用例如void Index(){}[HttpPost]void Index(一些参数){}ASP.NET MVC将看到传入请求,该请求将是GET或POST HTTP谓词[在本例中],并根据所看到的HTTP谓词将请求定向到上述任一控制器方法。