本質上,我需要創建一個具有用戶輸入三個整數的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>
「使用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