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(); } } }