苏飞论坛

标题: 关于ActionResult Controller中返回js alert背景为白色或者黑色问题解决方案 [打印本页]

作者: 一级菜鸟    时间: 2013-5-28 17:17
标题: 关于ActionResult Controller中返回js alert背景为白色或者黑色问题解决方案
这个问题纠结了很久,在网上找方法,有两种方式,一种是通过jsonResult去返回,一种是通过下面这种方式,我自己写了个class,代码如下:
[code=csharp]private HttpServerUtils() { }

        /// <summary>
        /// 服务端回馈给客户端的提示信息
        /// </summary>
        /// <param name="alertMessage">提示信息</param>
        /// <param name="redirectUrl">重定向地址,默认为当前页面</param>
        /// <returns></returns>
        public static ContentResult ResponseToClient(String alertMessage, String redirectUrl = "#")
        {
            ContentResult cr = new ContentResult();
            String content = "<script type='text/javascript'>alert('" + alertMessage + "');{0}</script>";
            if ("#".Equals(redirectUrl))
            {
                content = String.Format(content, "history.go(-1);");
            }
            else
            {
                content = string.Format(content, "window.location.href='" + redirectUrl + "'");
            }
            cr.Content = content;
            return cr;
        }

        /// <summary>
        /// 直接返回javascript的可执行代码
        /// </summary>
        /// <param name="jsCode"></param>
        /// <returns></returns>
        public static ContentResult ResponseJavascriptToClient(String jsCode)
        {
            ContentResult cr = new ContentResult();
            cr.Content = String.Format("<script type='text/javascript'>{0}</script>", jsCode);
            return cr;
        }[/code]

然后在Controller中return HttpServerUtils.ResponseToClient("提示语!");

但是这种效果令人不满意,输出时,背景为白色或者灰色(浏览器不同显示不同),而不是前一个界面。这是因为return时瞬时的,不会等view display了后再去Alert。效果图如效果图1所示:

后面通过自己研究,发现了一个比较简单的方法,可以在Controller加ViewBag.js,例如ViewBag.js = "<script type='text/javascript'>alert('提示语!');{0}</script>";
然后在View层用@Html.Raw(ViewBag.js)打印出来就OK了。虽然很简单,但希望大家还是少走弯路,尽快能够解决问题。~~


作者: 站长苏飞    时间: 2013-5-28 21:48
强烈支持楼主ing……




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4