Why does Glass Mapper return null values?

I am using Glass V4. I have an MVC Web Area Project.

I installed Glass Mapper in the Main project (WebProject).

I am trying to do Glass Casting in my project.

 public class ContactController : SitecoreController
{
    private readonly ISitecoreContext _context;
    private IGlassHtml _glassHtml;

    public ContactController()
        : this(new SitecoreContext())
    {

    }
    public ContactController(ISitecoreContext context)
    {
        _context = context;
        _glassHtml = new GlassHtml(context);

    }

    // GET: Contact
    public ActionResult ContactUs()
    {
        var db = Sitecore.Context.Database;
        var datasource = db.GetItem(RenderingContext.Current.Rendering.DataSource);

        var ViewModel = new Models.ContactUs();
        ViewModel.Headerstring = datasource.Fields["Headerstring"].Value;
        ViewModel.Substring = datasource.Fields["Substring"].Value;
        ViewModel.Description = ((MultilistField)datasource.Fields["Description"]).GetItems().Select(s => s.Fields["Line"].Value).ToList<string>();

        return View(ViewModel);
    }

    public ActionResult ContactUsGlass()
    {
        var model = _context.GetCurrentItem<ContactUsGlassModel>();
        return View(model);
    }
}

I can get the value using the First Action method, but not with the second.

Model:

public class ContactUs
{
    public string Headerstring { get; set; }
    public string Substring { get; set; }
    public List<string> Description { get; set; }
}

Glass Model:

public class ContactUsGlassModel
{
    public virtual string Headerstring { get; set; }
    public virtual string Substring { get; set; }
}

I understand that I do not need to register my namespace in Glass V4.

+4
source share
3 answers

You cannot use the method _context.GetCurrentItem. Use instead _context.GetItem:

public ActionResult ContactUsGlass()
{
    var model = context.GetItem<ContactUsGlassModel>(RenderingContext.Current.Rendering.DataSource);
    return View(model);
}

You do not want to get the model from yours Sitecore.Context.Item(which is used in the method GetCurrentItem). You want to get your model from the DataSource of the current rendering.

+5

@Marek - . GetCurrentItem , Sitecore. , , , GetCurrentItem . Datasource , , Sitecore .

0

GlassController, GetLayoutItem(), . , sitecore , , TDS:)

0

Source: https://habr.com/ru/post/1614831/


All Articles