Comments (8)
Your ModelData
assignment is an anonymous object, but as you can see, the property ModelData
is actually of type System.Object
. This is the type that is used as the model type, and it is correctly reporting that object
does not contain the name
property.
You could potentially switch to using public dynamic ModelData { get; set; }
instead, otherwise I'm not sure I can see a clean way of doing it?
Or, you could use a method such like:
public RenderModel CreateRenderModel<T>(string template, T model)
{
return new RenderModel<T>() { Template = template, ModelData = model };
}
With a redefined container:
public class RenderModel<T>
{
public string Template { get; set; }
public T ModelData { get; set; }
}
Usage:
return View(CreateRenderModel("Hello @Model.name", new { name = "Brian" }));
You may have to change your view to View<dynamic>
to support the generic model though.
from razorengine.
I had some issue with that but I managed to get it to work by casting it back to a dynamic in the parse method. The problem is that in the HTML helper class you can't pass dynamic objects otherwise the page just crashes.
This is what I ended up doing
public static IHtmlString RenderTemplate(this HtmlHelper helper, string template, T model)
{
return helper.Raw(RazorEngine.Razor.Parse(template, (dynamic)model));
}
from razorengine.
In honesty though, you'll find improved performance if you just provide statically typed models (not dynamic/anonymous models) as there is some additional work we have to do to support these scenarios, statically typed models will always perform better and do not require the overhead of the DLR to use them.
from razorengine.
Ya I understand that and am looking into that, but my goal is to use this in a plugin system where the types are specified in the plugin itself and may not be known to the core application. I am working on a way to change that fact or another method. Mainly just doing POC now to see if the scenario is going to work for me. Thank you for your help.
from razorengine.
I have another question, please let me know if I should open another topic.
When passing a type with a list property, I am getting the following exception
ContractException was unhandled by user code
Precondition failed: templateType != null
RazorEngine.Razor.Compile(t.TemplateData, t.Model.GetType(), t.TemplateName);
--Erros on the Run method
ViewBag.Content = RazorEngine.Razor.Run(t.TemplateName, t.Model);
from razorengine.
Hmm, can you show me some more code?
from razorengine.
Sure. I am trying to load data from a plugin. I have created my won plugin system and for testing purposes am loading them from the Controller action. Here is my code from the controller.
To clarify one thing too, I tested this class loaded in a single application and it parsed fine. Seems to be just when it is loaded in the plugin assembly.
This method of loading the plugin methods is messy and has a lot of overhead but it works for my testing purposes.
public ActionResult Render(string pageName, string template)
{
ITemplate t = null;
foreach (var plugin in PluginManager.LoadPlugins("~/Plugins"))
{
t = plugin.GetTemplate(template);
if (t != null)
break;
}
if (t != null)
{
try
{
ViewBag.Content = t.CompileTemplate();
}
catch (Exception ex)
{
ViewBag.Content = ex.Message;
}
}
else
{
ViewBag.Content = "Template is null...";
}
return View();
}
The rest of this code is inside the loaded plugin DLL
public class TestModelList
{
private List<TestModel> _items;
public List<TestModel> Items
{
get
{
if (_items == null)
_items = new List<TestModel>();
return _items;
}
}
}
public class TestModel
{
public int ID { get; set; }
public string SomeShit { get; set; }
public DateTime EnterDate { get; set; }
}
public class TestTemplate : ITemplate
{
public string TemplateName { get; set; }
public string TemplateData { get; set; }
public dynamic Model { get; set; }
public string CompileTemplate()
{
if (this.TemplateData != null && this.Model != null)
{
return Razor.Parse(this.TemplateData, (TestModelList)this.Model);
}
else
{
return "Template data is incomplete. Parsing aborted...";
}
}
}
public class Plugin : PluginBase
{
public Plugin()
{
this.Name = "Test";
TestTemplate t = new TestTemplate();
t.TemplateName = "List";
t.TemplateData =
@"<ul>
@foreach( var item in Model.Items){
<li>@item.SomeShit (@item.EnterDate)</li>
}
</ul>";
TestModelList list = new TestModelList();
list.Items.Add(new TestModel() { EnterDate = DateTime.Today, ID = 1, SomeShit = "This is a test" });
t.Model = list;
this.Templates.Add(t);
}
}
The LoadPlugins method
public static List<IPlugin> LoadPlugins(string virtualPath)
{
List<IPlugin> plugins = new List<IPlugin>();
foreach (var plug in Directory.GetFiles(HostingEnvironment.MapPath(virtualPath), "*.dll", SearchOption.AllDirectories))
{
Assembly assembly = Assembly.Load(AssemblyName.GetAssemblyName(plug));
var pluginAttribute = (PluginDefinition)assembly.GetCustomAttributes(typeof(PluginDefinition), false).FirstOrDefault();
if (pluginAttribute != null)
{
var type = assembly.GetType(pluginAttribute.IPlugInObjectType);
var instance = Activator.CreateInstance(type) as IPlugin;
plugins.Add(instance);
}
}
return plugins;
}
from razorengine.
If this is still a problem please open a new issue as the initial issue seems to be resolved/explained (sorry but I try to clean up the issue list).
from razorengine.
Related Issues (20)
- RazorEngine Render ViewComponent And TagHelpers
- - error: (25, 6) The name 'model' does not exist in the current context - error: (18, 19) There is no argument given that corresponds to the required formal parameter 'componentContext' of 'ViewBase<InteractiveSubjectPageExportReport>.ViewBase(IComponentContext)'
- Image doesn't render HOT 1
- Anouncement: Security with `IsolatedRazorEngineService` HOT 4
- The name 'model' does not exist in the current context HOT 4
- Engine.Razor.Compile, Cant Locad Resource
- Vulnerability Remediation HOT 1
- How to fetch list of model keys from razor file?
- Exception 'Dynamic operations can only be performed in homogenous AppDomain'
- Build issue with v2 odata queries?
- When I use RazorEngine again, the input '' is transferred to&# 39. How can I solve this problem?
- action failed due to exception RazorEngine.Templating.TemplateCompilationException: Errors while compiling a Template.
- #115 The problem is not resolved in RazorEngine.NetCore HOT 3
- cshtml file with model in console app
- 'AppDomainSetup' does not contain a constructor that takes 0 arguments HOT 6
- encounter errors when use @Include in template
- Another Razor issue on flush with dynamic or anonymous types
- RazorEngine.Templating.TemplateCompilationException: error: (0, 0) An expression is too long or complex to compile
- Razor Nuget Packages for .NET 8.0 HOT 4
- System.Runtime.Serialization.SerializationException when call IsolatedRazorEngineService.Create() HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from razorengine.