Jonas Praem
Jonas Praem

Reputation: 2454

Can't access Model inside webform ascx file

I am trying to do a simple console log of a ascx model in the view of my presentation file.

<script>
    console.log("hello world", <%=Model%>);
</script>

I have defined the Model on line one as so

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Guide.ascx.cs" Inherits="Guide.Presentation.Form" %>

And for goodness sake, here is the code behind

namespace Guide.Presentation
{
    public partial class Form : ModelBoundUserControl<Model.Form>
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

The console log in the top comes out as

Uncaught TypeError: Cannot read property 'Form' of undefined

Meaning that the Presentation property is undefined. Is there anything wrong in the way I have setup the model in the ascx file? or is this a problem with the Sitecore model from which we get the data? Any ideas to what is happening?

Upvotes: 0

Views: 402

Answers (1)

Jan Bluemink
Jan Bluemink

Reputation: 3487

Looks like you project has some kind of framework on top of Sitecore, the ModelBoundUserControl.

In Sitecore ASP.NET Web Forms, You can get the Current Sitecore Item with:

Sitecore.Context.Item

If you use a Datasource you can get the Datasource Item with something like this.

Sublayout currentSublayout = this.Parent as Sublayout;
string DataSource = currentSublayout.DataSource;
item Item = Sitecore.Context.Database.GetItem(DataSource)

If you use an very old version of Sitecore than the Datasource is a path instead of a GUID.

If you have the Sitecore Item you can access the field for example

string Title =  item.Fields["Title"].Value;

Where Title is the Field name, you can also use the GUID. Basically there is no Model you have an generic Sitecore Item Object.

Upvotes: 0

Related Questions