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(); } } }
@{ 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>