Obtain form data through model binding basic types

  1. Write the view page, set the name attribute for the input tag, the core code is as follows:
<div>
        <form action="/Demo2/Index" method="post">
            <div>账号:<input type="text" name="id" value="@ViewBag.id" /></div>
            <div>评分:<input type="text" name="score" value="@ViewBag.score" /></div>
            <div>评论:<textarea name="comment" cols="50" rows="10">@ViewBag.comment</textarea></div>
            <input type="submit" value="提交" />
            <h2>@ViewBag.Info</h2>
        </form>
    </div>
  1. Write the Index() operation method with parameters in the controller. The parameter name is the same as the name attribute value of the input tag to achieve the default model binding. The core code is as follows:
public class Demo2Controller : Controller
    {
    
    
        // GET: Demo2
        public ActionResult Index()
        {
    
    
            return View();
        }
        [HttpPost]
        public ActionResult Index(string id,int? score,string comment)//基本类型绑定
        {
    
    
            ViewBag.id = id;
            ViewBag.score = score;
            ViewBag.comment = comment;
            ViewBag.Info = $"{id}提交的评论信息是{comment},评分是{score}分";
            return View();
        }
    }

Guess you like

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