- Published on
Defining which Controller Action or Json route to POST to when there's more than one on the page
- Authors
- Name
- Steve McNiven
- @stevemcniven
Sitefinity Controllers are fantastic, you can easily expose public properties and the designers handle saving your preferences back. But what happens when you have 2 controllers on the page, and they both specify the route of Foo
[HttpPost]
public JsonResult Foo()
{
return Json(new {
data = this.SomeProperty
});
}
- Widget Instance 1 this.SomeProperty is set to “Steve”
- Widget Instance 2 this.SomeProperty is set to “Dave”
So think about this now, if our page is /bar, and this widget exists on that page TWICE, how would one POST back to /foo/bar and get back Steve if you want Steve, or Dave if you want Dave.
What will happen by default at /foo/bar is it’s going to give you the first Controller instance, in this case you’re ALWAYS going to get “Steve”.
So how do we find Dave?
It’s actually REALLY simple, Sitefinity allows you to pass in the control id of Controller you want right on the querystring with sf_cntrl_id
axios.post("/foo/bar?sf_cntrl_id=" + thewidgetid)
Now we’re getting Dave back
The only missing piece is how to get that ControlId? Well it’s all done for you just part of the ViewData, Sitefinity automatically adds it!
public string ControlDataId
{
get
{
var controlDataId = "";
var keyName = Telerik.Sitefinity.Mvc.Proxy.MvcControllerProxy.ControllerKey;
if (this.ViewData != null && this.ViewData.ContainsKey(keyName))
{
controlDataId = this.ViewData[keyName].ToString();
}
return controlDataId;
}
}
That’s all there is to it!
Oh, one thing to note, the Html.BeginFormSitefinity helper will AUTOMATICALLY add the controlId stuff in for you in the current instance it’s cshtml runs under… but you can’t BeginFormSitefinity an XHR post as well obviously.