Sitecore SPEAK - set searchdatasource root programmatically - javascript

I have been playing with SPEAK dialogs lately. So far I like it, but have stumbled across an issue. I have passed with an itemID in the url parameters and I want to display the children of this item in a listcontrol.
My approach was to create a SearchDataSource and set the field "rootItemId" via javascript. This doesn't seem to work. Is there a way to access the SearchDataSource's rootItemId in the PageCode?

Another way I've been using lately is to use Anders Laub's JSON Datasource control here. http://laubplusco.net/creating-simple-sitecore-speak-json-datasource/.
From the JavaScript PageCode you can then do a Ajax call and append in JSON result items to populate your listcontrol, where the listcontrols is bound to the JSON datasources Json property.
$.ajax({
url: "/api/sitecore/RolePermissions/GetAllRoles",
type: "POST",
context: this,
success: function (data) {
var json = jQuery.parseJSON(data);
for (var i = 0; i < json.length; i++) {
var obj = json[i];
this.JsonDS.add(obj);
}
}
});

I managed to do this with query. In pageCode:
public class SelectTitle : PageCodeBase
{
//Fetches DataSource as rendering
public Rendering DataSource { get; set; }
public override void Initialize()
{
var articleid = WebUtil.GetQueryString("article");
if (!String.IsNullOrEmpty(articleid))
{
//Set the query.
this.DataSource.Parameters["query"] =
String.Format("fast:/some/path/*[##id = '{0}']/Elements/*[##templateid = '{1}']", articleid, '{guid}');
}
}
}

Related

Passing JSON array in AJAX call sending null in MVC

I am trying to pass an array of json objects to my controller action and it keeps coming in as null.
Javascript Code
function UpdateSelected() {
var items = {};
//Loop through grid / sub grids and create json array
$('.k-detail-row .k-grid').each(function () {
var grid = $(this).data("kendoGrid");
var selectedElements = grid.select();
for (var j = 0; j < selectedElements.length; j++) {
var item = grid.dataItem(selectedElements[j]);
var json = item.toJSON();
items = [].concat(items, json);
}
})
//shift the first empty space out
items.shift();
//items is ready to send
alert(JSON.stringify(items));
$.ajax({
cache: false,
url: '/Update/GetSchematicsForSelectedVariants',
type: 'GET',
data: JSON.stringify(items),
success: function (data) {
alert("success");
}
});
}
The Json array looks like this:
Controller Action
public JsonResult GetSchematicsForSelectedVariants(List<VariantViewModel> vm)//vm coming in null
{
return Json(_dataAccessService.GetSchematicsForMacroVariants(vm),JsonRequestBehavior.AllowGet);
}
VariantViewModel
public class VariantViewModel
{
public string Id { get; set; }
public string Variant { get; set; }
}
So I am not to sure what is going wrong here. My list is being passed in as null. I am not to keen on passing json objects to the controller but I believe I have the gist of what I need.
Could someone please point me in the right direction?
I found the issue. My data needed to be passed in the following way in my AJAX request. Can't believe I missed this honestly.
$.ajax({
cache: false,
url: '/Update/GetSchematicsForSelectedVariants',
type: 'POST',
data: {'ListOfVariants' : items},
success: function (data) {
alert("success");
}
});
Thank you everyone for your comments it helped point me in the right direction.

Parsing Json data from asp.net webservice and populating it in asp.net dropdownlist

i am trying to populate an asp.net dropdownlist returned as JSON from my webservice.
WebService
[WebMethod(EnableSession = true)]
public string GetActiveDepositAccountsForLoanAlert(string customerId)
{
var data = BusinessLayer.SMS.SmsSetup.GetActiveDepositAccountsForLoanAlert(customerId.ToLong());
var json = new JavaScriptSerializer().Serialize(data);
return json;
}
The webservice returns
[{"AccountNumber":"NS-0000092"},{"AccountNumber":"6MR-0000002"},{"AccountNumber":"1YFD-0000007"}]
I am calling the data from ajax call and populating it to my dropdownlist.
Ajax call
function GetActiveDepositAccounts(customerrId) {
var customerId = $('#CustomerIdHiddenField').val();
var data = { customerId: $('#CustomerIdHiddenField').val() };
var json_data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "/WebMethods/Misc.asmx/GetActiveDepositAccountsForLoanAlert",
data: json_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(r) {
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i] + '</option>');
}
}
The data gets populated in json.In my dropdown i only want the accountnumber as
NS-0000092.I am getting the whole json in my dropdown.i have searched and seen lots of question with this Json parse thing in here.But couldnt get hold of this.It isnt that i didnt tried,I am newbie,so before marking this as duplicate,please for once have a look at the code.Thank you.
I can't shake the feeling that because your GetActiveDepositAccountsForLoanAlert is returning a string and not an object, r.d is being seen as a string. Try one of 2 things. Either:
Change your method signature to return data type and don't use the JavaScriptSerializer. or,
In your OnSuccess function, add var data = JSON.parse(r.d) and use that variable in your for loop.
Single Object Returned
If by "whole json", you mean you are getting a single {"AccountNumber":"6MR-0000002"} per option -- try outputting the value of the target AccountNumber object (e.g. r.d[i].AccountNumber or r.d[i]["AccountNumber"]).
Modified Function
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i].AccountNumber + '</option>');
}
Array of Objects Returned
If the result per option is an entire AccountNumber array of objects, you'll need to loop through your r object until you get to the list of Account Number objects.
Take a look at my Example JS Fiddle. There is probably a cleaner way to do this, but to present the principle, I've laid out nested loops to get you into the list of object values that you need for your <select></select>.
I'm using the JQuery $.each() method, but you can use the for loop. I recommend just using one or the other for consistency. If the data set is really large, for loops have better performance.

$http Call to Web API 2 Not Passing Parameter

This is my C# WebAPI2 controller, which gets hit:
[HttpGet, Route("bycaseidlist/{idArray}")]
public async Task<IHttpActionResult> GetByCaseIdList([FromUri] List<int> idArray)
This is the call:
var idArray = [4,4,2,4];
var url = baseUrl + 'api/cases/bycaseidlist/' + idArray ;
$http.get(url)
The problem is that the API doesn't get the array, it gets ...this:
In other words an array with one value: 0. Why is this happening? How do I fix it? It seems to be in-line with this answer, but it doesn't work. Should I pass it in the body? I feel like I am missing something obvious.
Get ActionMethods can take objects as arguments. However, the default behavior is to look at the body when the parameter is not a .net primitive. In order to force the action method to use a model binder to read the object data from the request, the parameter can be decorated with the [FromUri] or [ModelBinder] attributes. (Note there are other ways to do this that include doing parameter binding rules but that is probably overkill for what you are trying to accomplish here). Here is an implementation that solves the original problem that you were posing.
<script type="text/javascript">
var ajaxCall = function (myArry) {
var ajaxProperties = {};
ajaxProperties.url = "/api/Mul/Mutiply";
ajaxProperties.type = "Get";
ajaxProperties.data = {};
ajaxProperties.data.numbers = myArry;
ajaxProperties.contentType = "application/json";
console.log(ajaxProperties);
ajaxProperties.success = function (data) {
console.log(data);
}
ajaxProperties.error = function (jqXHR) {
console.log(jqXHR);
};
$.ajax(ajaxProperties);
};
var getData = function (e) {
var myArry = new Array();
myArry.push($('input[name=num1').val());
myArry.push($('input[name=num2').val());
ajaxCall(myArry);
return false;
};
</script>
Controller
[HttpGet]
public IHttpActionResult Multiply([FromUri] int[] numbers)
{
int result = 0;
if(numbers.Length > 0)
{
result = 1;
foreach (int i in numbers)
{
result = result * i;
}
}
return Ok(result);
}
}
I think my mistake was using Get. I might be remembering incorrectly (someone confirm if you know offhand), but Get might not be able to take objects as arguments. Anyway, I changed the method to POST and then changed the param to be sent in the request body, rather than the url. It now works. Here is the working code:
[HttpPost, Route("bycaseidlist")]
public async Task<IHttpActionResult> PostByCaseIdList([FromBody] int[] sqlCaseIdArray)
and the call itself:
function runDbCall(url, sqlCaseIdArray){
return $http({
method: 'POST',
url: url,
data: sqlCaseIdArray
});
}
runDbCall(url, sqlCaseIdArray)
I will come back to this when I figure out if the problem was Get not being able to take objects, but I thought it could in url, just not in body...need to clarify. If someone posts an answer just on that part, I will accept, since that's probably the root of the prob.

Pass array of objects containing arrays to MVC action via javascript

Say I have a javascript object like:
function Parent(n, c) {
this.Name = n;
this.Children = c;
}
var p = new Parent("asdf", [1,2,3]);
And I want to pass an array of the parent object and its children to an MVC 4 controller via JSON.
How would I go about formatting the ajax request? I've seen quite a few other questions along these lines, although none that use an array as a member variable.
This is what I have so far:
var parents = [];
parents.push(new Parent("qwer", "child1"));
parents.push(new Parent("sdfg", 12345));
parents.push(new Parent("zxcv", [4,5,6]));
$.ajax({
url: MakeUrl("Ctlr/Action"),
type: "POST",
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({
parents : parents
}),
success: function (data, state, xhr) {
$("#someDiv").html(data);
},
error: function (xhr, state, err) {
Utility.displayError(xhr.reponseText);
}
});
The result of stringify actually looks reasonable:
"{"parents":[{"Name":"qwer","Value":"child1"}, {"Name":"sdfg","Value":12345}, {"Name":"zxcv","Value":[4,5,6]}]}"
Here is the Controller action:
public ActionResult Action(IEnumerable<Parent> parents) {
...
}
And in case it's relevant, the server-side Parent object:
public class Parent {
public string Name { get; set; }
public object Children { get; set; }
}
Children is an object because it is sometimes another data type - I realize this may be a slight code-smell, but the ultimate function of this class is to pass arbitrary parameters to our reporting engine.
The simple data types seem to work just fine in this way (date, integer, string, etc), but the Children array just comes through as {object}, which as far as I can tell is not even a string, but some generic System object. Is there a way to do this in MVC without resorting to, say, pushing it into a string and parsing it out?
For now, I've settled for submitting a flat list via javascript, which is then built out on the server side.
The javascript:
var parents = [];
parents.push(new Parent("asdf", "qwer"));
parents.push(new Parent("zxcv", 123456));
[4,5,].forEach(function (e, i) {
params.push(new Parent("Children[" + i + "]", e));
});
Which looks like this after JSON.stringify:
[{"Name":"asdf","Value":"qwer"},{"Name":"zxcv","Value":123456},{"Name":"Children[0]","Value":4},{"Name":"Children[1]","Value":5},{"Name":"Children[2]","Value":6}]
And is then un-flattened in the Controller via the following function:
private IEnumerable<Parent> Unzip(IEnumerable<Parent> parameters) {
var unzipped = new Dictionary<string, Parent>();
var r = new Regex(#"(.*)\[.*\]");
foreach (var p in parameters)
{
var match = r.Match(p.Name.ToString());
if (match.Success)
{
var name = match.Groups[1].Value;
if (!unzipped.ContainsKey(name))
unzipped.Add(name, new Parent() { Name = name, Value = new List<object>() { } });
((List<object>)(unzipped[name].Value)).Add(p.Value);
}
else
unzipped.Add(p.Name, p);
}
return unzipped.Values;
}

How to parse a JSON object ? (From server-side to client-side...javascript)

I have a jquery interacting with a server side Web Method. The Web method accepts a string 'memID' from the jquery and executes SQL queries based on it. Then I create a class:-
public class Member
{
// Objects of Member. //
public string id { get; set; }
public string HPCode { get; set; }
public string OPfromDate { get; set; }
public string OPthruDate { get; set; }
public Member(string ID, List<string> hpCode, List<string> opfromDate, List<string> opthruDate)
{
id = ID;
for (int j = 0; j < hpCode.Count; j++){ HPCode = HPCode + (hpCode)[j] + '*' };
for (int j = 0; j < opfromDate.Count; j++){OPfromDate = OPfromDate + (opfromDate)[j] + '*' };
for (int j = 0; j < opthruDate.Count; j++){OPthruDate = OPthruDate+ (opthruDate)[j] + '*' };
}
}
This class is used to return the results of my SQL query to the client side:-
return JsonConvert.SerializeObject(member);
I used breakpoints and checked on the client side, indeed it is getting the return values. However I am not sure about what is the best way to parse these values and store them in variables on my javascript side so i can use them for client-side functionalities.
// Ajax function that sends member ID from client side to server side without a post back.
function ajax()
{
$.ajax
({
url: 'Default.aspx/MyMethod',
type: 'POST',
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ memID: mem_ID }),
success: onSuccess,
fail : onFail
});
}
// If client-to-server communication is successful.
function onSuccess(data)
{
confirm(data.d);
var returnedstring = (data.d);
var jsondata = $.parseJSON(data.d);
}
Now how do I parse the 'data' ?? is there an eval function? or parse function?
Does anybody have any web examples? before this I was only passing back 1 value to my client side, so it was easy to get, now i am confused with multiple values.
UPDATE:-
I tried doing this on my javascript side:-
var returnedstring = (data.d);
var member = data.d.id;
var Hp = data.d.HPCode;
however when I use breakpoints and hover over them with my mouse, i get member and HP as undefined, however the returnedstring has all the correct values.. ... any idea?
SOLUTION (I couldn't figure out the other way suggested in the answers, but this works for me) :-
function onSuccess(data)
{
// stores entire return in one string.
var returnedstring = (data.d);
// parses json returned data
var jsondata = $.parseJSON(data.d);
var member = jsondata.id;
var HpCode = jsondata.HPCode;
}
Because you're using dataType: "json", data is already parsed out of the JSON string. That's why you're able to access data.d in Javascript.
To access the members, you can do something like this:
console.log(data.d.HPCode);

Categories