//腳本化的C#想寫對仍是有點麻煩的,還好Razor能給出有用的錯誤信息。public class RazorPropertySetter<TEntity> where TEntity :class { string PropertyName; bool Inited = false; private RazorPropertySetter(){ } public static RazorPropertySetter<TEntity> Create( string propertyName) { RazorPropertySetter<TEntity> rs = new RazorPropertySetter<TEntity>(); rs.PropertyName = propertyName; return rs; } public void Set(TEntity entity , object value) { string cacheKey = entity.GetType().FullName + "--" + this.PropertyName; DynamicViewBag viewBag = new DynamicViewBag(); viewBag.AddValue("PropertyValue", value); if (Inited == false) { string template = "@{Model."+PropertyName+ "= ViewBag.PropertyValue;}"; Engine.Razor.RunCompile(template, cacheKey, typeof(TEntity), entity,viewBag); Inited = true; } else { Engine.Razor.Run(cacheKey, typeof(TEntity), entity, viewBag); } } }