- 编写视图页面,为input标签设置name属性,核心代码如下:
<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>
- 编写控制器中带参数的Index()操作方法,参数名称与input标签的name属性值同名,以实现默认的模型绑定,核心代码如下:
public class Demo2Controller : Controller
{
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();
}
}