- Notifications
You must be signed in to change notification settings - Fork 101
@Html implementation example
Alexander edited this page Jan 11, 2021
·
2 revisions
@Html is a part of Mvc therefore it is absent in RazorEngine. @Html does a lot of things internally like accessing ViewState, Routes etc so you cant use it simply referencing AspNet.Mvc namespace.
In order to use @Html in template it must contain initialized public HtmlHelper<T> Html { get; set; } property
publicclassTestModel{publicstringStudentId{get;set;}}publicclassMvcTemplate<T>:RazorEngineTemplateBase<T>{publicMyHtmlHelper<T>Html{get;set;}}publicclassMyHtmlHelper<T>{privatereadonlyMvcTemplate<T>templateInstance;publicMyHtmlHelper(MvcTemplate<T>templateInstance){this.templateInstance=templateInstance;}publicstringHidden(Expression<Func<T,object>>selector){objectpropertyValue=selector.Compile()(this.templateInstance.Model);MemberExpressionbody=(MemberExpression)selector.Body;stringname=HttpUtility.HtmlAttributeEncode(body.Member.Name);stringvalue=HttpUtility.HtmlAttributeEncode(propertyValue?.ToString()??"");return$"<input type=\"hidden\" name=\"{name}\" value=\"{value}\"\\>";}}classProgram{staticvoidMain(string[]args){stringcontent=@" <p>hidden: @Html.Hidden(m => m.StudentId)</p> ";RazorEnginerazorEngine=newRazorEngine();varcompiledTemplate=razorEngine.Compile<MvcTemplate<TestModel>>(content);stringresult=compiledTemplate.Run(template =>{template.Model=newTestModel(){StudentId="<script>alert(\"1\");</script>"};template.Html=newMyHtmlHelper<TestModel>(template);});Console.WriteLine(result);Console.ReadKey();}}