Obtain form data through model binding

  1. Create a product data model class in the Models directory, including attributes: Name (product name) and Num (product quantity). The reference code is as follows:
public class Product
    {
    
    
        public string PName {
    
     get; set; }
        public int PNum {
    
     get; set; }
    }
  1. Write the form in the view page Home/Index.cshtml, the code is as follows:
<div> 
        <form action="/Home/Index" method="post">
            <div>名称:<input type="text" name="PName" value="@ViewBag.name" /></div>
            <div>数量:<input type="text" name="PNum" value="@ViewBag.num"/></div>
            <input type="submit" value="提交" />
            <h2>@ViewBag.ProductInfo</h2>
        </form>
    </div>
  1. Write the controller HomeController, use the default model binding to obtain model object data, the code is as follows:
public class HomeController : Controller
    {
    
    
        // GET: Home
        public ActionResult Index()
        {
    
    
            return View();
        }
        [HttpPost]
        public ActionResult Index(Product p)
        {
    
    
            ViewBag.name = p.PName;
            ViewBag.num = p.PNum;
            ViewBag.ProductInfo = $"您选择了名称为{p.PName}的商品{p.PNum}件";
            return View();
        }
    }

Guess you like

Origin blog.csdn.net/m0_47675090/article/details/106564185