views:

34

answers:

2

Hi!

Im creating a usercontrol which is controled client side, it has an javascript-file attatched to it. This control has a button and upon click a popup appears, this popup shows a list of my domain entities. My entities are fetched using a call to a webservice.

Im trying to get this popup usercontrol to work on all my entities, therefore i have the need to call any webservice needed (one per entity for example) with the same $.ajax() call.

I have hiddenfields for the webservice url in my usercontrol which you specify in the markup via a property. So far so good. The problem arise when i need some additional parameters to the webservice (other than pagesize and pageindex). Say for example that one webservice takes an additional parameter "Date".

At the moment i have my parameters set up like this:

    var params = JSON.stringify({
        pageSize: _this.pageSize,
        pageIndex: _this.pageIndex            
    });

and then i call the webservice like so:

$.ajax({
    webserviceUrl,
    params,
    function(result) { 
          //some logic
    });
});

What i want to do is to be able to add my extra parameters (Date) to "Param" when needed, the specification of these parameters will be done via properties of the usercontrol.

So, bottom line, i have a set of default parameters and want to dynamically add optional extra parameters.

How is this possible?

Thanks in advance.

A: 

something like this should work

var params = getDefaultParams();
// some condition to determine if extra needed?
params.specialDate = getSpecialDateParam();
// could also be written as params['specialDate'] = getSpecialDateParam();

$.ajax({
    webserviceUrl,
    JSON.stringify(params),
    function(result) { 
          //some logic
    });
});


// ****************************
function getDefaultParams () {
    return {
        pageSize: _this.pageSize,
        pageIndex: _this.pageIndex        
    };
}
house9
Thanks, this would work if i knew all the params, thanks anyway!
Andreas
+1  A: 

I know it won't be fast, but something like

var params;
function buildJsonParams(defaultParam1, defaultParam2, optionalParam1, ...)
{
  string pString = "params = JSON.stringify({ pageSize: _this.pageSize, pageIndex: _this.pageIndex";
  if (optionalParam1 != undefined)
  {
    pString += ",yourOptionParam: optionalParam1";
  }
  pString += "});";
  eval(pString);
}

or if you don't know ahead of time what the optional parameters are you could use parallel arrays, one being the variable and the other the parameter name and pass those into a buildJSONParams like function to do the same kind of thing only it loops through the 2 arrays that get passed in.

Greg
Thanks, this helped alot!
Andreas