MVCHelper 请求检验

 

    public class MVCHelper
    {
        //有 两 个ModelStateDictionary类,别弄混乱了要使用 System.Web.Mvc 下的
        //如果添加引用中找不到System.Web.MVC,那么可以用nuget安装:
        //Install-Package Microsoft.AspNet.Mvc
        public static string GetValidMsg(System.Web.Mvc.ModelStateDictionary modelState)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var key in modelState.Keys)
            {
                if (modelState[key].Errors.Count <= 0)
                    continue;

                sb.AppendFormat(" 属性【{0}】错误:", key);
                foreach (var modelError in modelState[key].Errors)
                {
                    sb.AppendLine(modelError.ErrorMessage);
                }
            }
            return sb.ToString();
        }
        
        public static string RemoveQueryString(NameValueCollection nvc, string name)
        {
            NameValueCollection newNvc = new NameValueCollection(nvc);
            newNvc.Remove(name);
            return ToQueryString(newNvc);
        }

        public static string UpdateQueryString(NameValueCollection nvc, string name, string value)
        {
            NameValueCollection newNvc = new NameValueCollection(nvc);
            if (newNvc.AllKeys.Contains(name))
                newNvc[name] = value;
            else
                newNvc.Add(name, value);

            return ToQueryString(newNvc);
        }

        private static string ToQueryString(NameValueCollection newNvc)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var key in newNvc.AllKeys)
            {
                string value = newNvc[key];
                //EscapeDataString就是对特殊字符进行uri编码
                sb.AppendFormat("{0}={1}&", key, Uri.EscapeDataString(value));
            }
            return sb.ToString().Trim('&');//去掉最后一个多余的&
        }

        //生成XXX的静态html页面的 方法
        public static string RenderViewToString(ControllerContext context, string viewPath, object model = null)
        {
            ViewEngineResult viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
            if (viewEngineResult == null)
                throw new FileNotFoundException("View" + viewPath + "cannot be found.");

            var view = viewEngineResult.View;
            context.Controller.ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
                view.Render(ctx, sw);
                return sw.ToString();
            }
        }
    }

 

转载于:https://www.cnblogs.com/kikyoqiang/p/10825726.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值