What is the best way to get currentBlock in block ajax call?
[HttpGet]
public ActionResult GetSomething()
{
var currentBlock = Get(); //how?
return currentBlock.SomeLabel;
}
(I don't know the solution when Block or BlockController do not know about the Page)
I want to make blocks reusable for any page.
Thanks.
I think you'd have to pass in the content reference for the block, but that isn't so bad.
To start with, make sure your
global.asaxclass includes the standard mvc route in the override for theRegisterRoutesmethod:I have a block that I've used for testing some things out; it has a Title property and Items - a list of content references.
For this block, I'll create a view model that contains those properties plus a ContentReference property. You can probably do this inside your cshtml view file, but this keeps your view a little cleaner.
Next, wire up the block's controller to use the view model. I'm also going to need some javascript files; those can be added here via the controller. See the Episerver documentation on Client Resources for more info on that.
On the view, make sure the content reference gets rendered in a place where the javascript can find it. I'm going to use a data attribute called
data-block-id.The javascript file referenced in the block controller would need to look for all block instances on the page, and then for each one, make the ajax call. Keep in mind that if your block is used on a page as a property then it won't have a
ContentLink, since block properties do not inheritIContent.Finally, the last thing to do would be to create the ajax method on the controller. This is going to expect a string parameter named "id" so that it conforms to the default MVC view we added back at the beginning. It's also going to use dependency injection on the controller to get an instance of
IContentLoader.