第一步創建一個實體類Product
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class Product
{
public string PName { get; set; }
public int PNum { get; set; }
}
}
第二步創建一個空的控制器
該控制器的代碼爲
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost] //這裏如果不標記會報錯的
public ActionResult Index(Product p)
{
//這裏用的實體類接收
ViewBag.ProductInfo = $"您選擇了名稱爲{p.PName},數量爲{p.PNum}";
return View();
}
}
}
第三步 右鍵添加視圖
第四步 Index頁面
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@*action的路徑要寫對, method爲post*@
<form action="/Home/Index" method="post">
@*name的名字必須與實體類的屬性相同*@
<div>名稱:<input type="text" name="PName" /> </div>
<div>數量:<input type="text" name="PNum" /> </div>
<input type="submit" value="提交" />
@*接收的參數*@
<h1>@ViewBag.ProductInfo</h1>
</form>
</div>
</body>
</html>