I have a normal MVC Controller (not a Sitecore Rendering) which I am calling in an AJAX request (from a Sitecore page). I need the current Sitecore item there. How can I access it there?
2 Answers
If it's an ajax call you just did from javascript to a normal MVC controller, there is no Sitecore.Context.Item there.
What you can do is in your original Sitecore rendering write the id of your item to the generated html (e.g. as a data-itemid
attribute) and then pass it with your ajax call back to the server. Thanks to that you will know which item you want to use.
In your cshtml file just use code like:
<div data-itemid="@Sitecore.Context.Item.ID">
Your rendering content
</div>
And in you javascript:
var data = {
ItemId = itemId,
OtherData = "foo",
OneMore = "bar"
};
$.ajax({
type: "POST",
url: url,
data: data
});
create class:
public class PostData
{
public string ItemId {get;set;}
OtherData {get;set;}
OneMore {get;set;}
}
and in your controller:
public ActionResult AcceptPost(PostData data){
var item = Sitecore.Context.Database.GetItem(data.ItemId);
}
This is just a sample - you should adapt this code to your scenario.
In Ajax requests the Sitecore.Context.Item object is NULL
. So you can't use it to get the current page.
To work around this, you will need to tell the MVC action what the current context item is using its ID. So you will need to pass this ID from the HTML into your MVC action.
public ActionResult SubmitForm(string firstName, string lastName, string pageId){
var page = Sitecore.Context.Database.GetItem(pageId);
// `page` variable now has a reference to your current page (Context Item)
}
The ID in the HTML is usually stored in a hidden input element or a data-attribute on some element.
e.g.
<input type="hidden" name="pageId" value="@Sitecore.Context.Item.ID.ToString()" />
OR
<div data-pageId="@Sitecore.Context.Item.ID.ToString()" >
Finally in your ajax request function, you will have to get the value of the pageID
and pass it into your ajax request