【新手上路】MVC3.0 怀疑razor视图引发的奇怪现象(求解答)

首先随便写一个实体类

    public class Student
    {
        public string Name { get; set; }
    }

然后添加两个action

        public ActionResult InsertStudent()
        {
            return View(new Student());
        }
        [HttpPost]
        public ActionResult InsertStudent(FormCollection forms)
        {
            Student stu = new Student();
            UpdateModel<Student>(stu);
            stu.Name = "张三";//改变updatemodel后的对象的属性的值
            return View(stu);//显示改变后的对象
        }

然后添加强类型razor视图

@model Teaching.Models.Student
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>InsertStudent</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.TextBoxFor(model => model.Name)
        @Model.Name
        <input type="submit" value="OK" />
    }
</body>
</html>

奇怪结果

在页面中的文本框中输入“李四”,然后点击ok按钮提交后,结果:页面的文本框中显示的仍然是“李四”,文本框后面则输出“张三”。

若注释掉“UpdateModel<Student>(stu);”后,重复以上操作,结果:页面的文本框及文本框后面都输出修改后的“张三”。

问:文本框后面两次输出的都是修改后的“张三”,说明从后台传到前台的值都是修改后的值“张三”,那为什么用了updatemodel之后,使用htmlhelper显示的还是修改之前的值呢?怀疑是razor视图机制引起的。请大家帮忙解释下。

原文地址:https://www.cnblogs.com/liuxinqi/p/2477474.html