WebPages 扩展
webpage 的 InitModel(初始化一个自定义类型)。
using Newtonsoft.Json; using System; using System.Web; using System.Web.WebPages; namespace FDOA.Webpages.Common { public static class WebPagesExtend { public static T InitModel<T>(this WebPage webPages) where T : new() { return InitModel(webPages, new T()); } public static T InitModel<T>(this WebPage webPages,T theClass){ var tempClassType = typeof(T); var tempClassProperties = tempClassType.GetProperties(); foreach (var i in tempClassProperties) { try { var requestValue = HttpContext.Current.Request[i.Name]; if (requestValue == null) { continue; } else { var propertyValue = Convert.ChangeType(requestValue, i.PropertyType); i.SetValue(theClass, propertyValue, null); } } catch { } } return theClass; } public static HtmlString ToJson(this object obj) { var result = JsonConvert.SerializeObject(obj); return new HtmlString(result); } } }
调用:http://localhost/Default?age=132
@{ var model1 = this.InitModel<UserInfo>(); var model2 = this.InitModel(new UserInfo() { // 如果 Request["userid"] == null 则赋值 UserId="default" , // 如果 Request["IsLocked"] == null 则赋值 IsLocked = true }); } @model1.ToJson() @model2.ToJson() @functions{ private class UserInfo { public string UserId { get; set; } public int Age { get; set; } public bool IsLocked { get; set; } } }