一个自己给自己挖的MVC的坑

  事情是这样的,我前几天突然想起没用过MVC提交之后刷新当前页面的方式更新View(一般情况是不会有人这么做的吧),我这人手快,就试了下,结果出现了个我想不明白的结果,Action代码如下:

        [HttpPost]
        public ActionResult STest(TestType type)
        {
            TestType display = new TestType() { AAA = type.AAA + "sa", SSS = "sss" };

            ViewData.Model = display;
            return View(display);
        }    

  View代码:

@model Models.TestType

@{
    ViewBag.Title = "STest";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>STest</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>TestType</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.AAA)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.AAA)
            @Html.ValidationMessageFor(model => model.AAA)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.SSS)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.SSS)
            @Html.ValidationMessageFor(model => model.SSS)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

  结果是,执行了action之后,页面没有变化,我加上去的"sa",木有加上去。。。

  我清缓存,调代码,还把源码下了(可能调试的不细),实在想不明白了,就上msdn上问,也没问出结果,正好明天不上班,晚上查查资料,聊天的时候,顺便问了一下,结果@netfocus一语惊醒梦中人:“因为页面显示不是走post的呀”。我突然反应过来,rest的定义中,post就不负责传数据给页面,浪费了好多时间啊,看来还是对rest的理解不够。

  特此纪念,同时也作为一个提醒,理论概念能很好的指导我们少走弯路。

=============咱是分割线=============

  今天,群里另外一个朋友从技术角度给出了解决办法,十分感谢Ivan,如果有朋友不得不这么做,可以参考下

ModelState.Clear();

  原因如下:

  • This is correct. This behavior is identical to the MVC 1.0 behavior.

    The reason we use the posted value for editors rather than the model value is that the model may not be able to contain the value that the user typed. Imagine in your "int" editor the user had typed "dog". You want to display an error message which says "dog is not valid", and leave "dog" in the editor field. However, your model is an int: there's no way it can store "dog". So we keep the old value.

    If you don't want the old values in the editor, clear out the Model State. That's where the old value is stored and pulled from the HTML helpers.

    大概意思是说,就是这么设计的,原因是你如果改的时候,传了一个不匹配的值,结果是连验证信息都可能显示不出来

    原帖地址:http://forums.asp.net/p/1527149/3687407.aspx

     

    再次最后,这种做法确实不好,跨过了页面验证,直接Post值,拦截了传输一般的数据,强行hack的行为,V和C在同一个过程中都对M产生了影响,难以保证副作用,而且过程不再单纯,给人一种触发器的感觉,相信大家很少在项目中使用触发器,或许这也是之后出现了MVP和MVVM的原因之一。

posted @ 2014-05-01 00:55  draculav  阅读(596)  评论(0编辑  收藏  举报