Note

1.Razor渲染顺序/事件(Ajax)执行顺序

1.Razor渲染顺序/事件(Ajax)执行顺序

The Razor pipeline is:


  1. First, Razor evaluates, if present, _ViewStart.cshtml that contains only Razor statements (C# or VB) for assign Layout or other initialization, it should never have html tags inside.

  2. Then, it parse and evaluates the "View" cshtml file.

  3. Then, it parse and evaluates, if present, the Layout, and when evaluates the @RenderBody method of the cshtml layout file, replaces it with the html script resulting from evaluation of "View" cshtml file.

  4. Finally, it builds the html control graph objects of layout and view html files.

//图片验证码
<img id="imgcode" src="@Url.Action("SecurityCode", "Agent")" />

//不能直接用@Session[SecurityCode]获取验证码的值
//HTML加载完成后, Razor会先从上到下渲染变量(图片处留空),最后进入图片src的路径
//这会导致图片加载完成前Session就取到了值(第一次为空,第二次开始取上一个验证码的值)
            $('#imgcode').mousedown(function () {

                this.src = this.src + '?';//刷新图片
            });

//这个异步方法有几率在图片刷新之前完成,所以不用click
            $('#imgcode').mouseup(function () {
                $.get('@Url.Action("SecurityCode", "Agent")')
                    .done(function (data) {
                        code = data.sessioncode;
                        //alert(code);
                    })
                    .fail(function (data) {
                        alert('Ajax code request fail');
                        alert(JSON.stringify(data));
                    });
            });

//后端代码
public ActionResult SecurityCode()
        {
            if (!Request.IsAjaxRequest())
            {
                string code = CreateRandomCode(4); 
                Session["SecurityCode"] = code; return File(CreateValidateGraphic(code), "image/Jpeg");
            }
            else
            {
                var CodeObject = new { sessioncode = Session["SecurityCode"] as String };
                return Json(CodeObject, JsonRequestBehavior.AllowGet);
            }
        }
 
原文地址:https://www.cnblogs.com/Jayesslee/p/9213828.html