Git Product home page Git Product logo

Unable to compile template. 'object' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) about razorengine HOT 8 CLOSED

antaris avatar antaris commented on July 30, 2024
Unable to compile template. 'object' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

from razorengine.

Comments (8)

Antaris avatar Antaris commented on July 30, 2024

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.

bhmahler avatar bhmahler commented on July 30, 2024

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.

Antaris avatar Antaris commented on July 30, 2024

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.

bhmahler avatar bhmahler commented on July 30, 2024

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.

bhmahler avatar bhmahler commented on July 30, 2024

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.

Antaris avatar Antaris commented on July 30, 2024

Hmm, can you show me some more code?

from razorengine.

bhmahler avatar bhmahler commented on July 30, 2024

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.

matthid avatar matthid commented on July 30, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.