通过模型绑定基本类型获取表单数据

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

猜你喜欢

转载自blog.csdn.net/m0_47675090/article/details/106564828
今日推荐