Passing few values through querystring, to testFn() in controller using below code. But in testFn, I am getting null values. When I keep alert on companyName, rdVal,etc. it is showing correct values. but those are not passing to controller. Please let me know what went wrong.
View:
#Html.ActionLink("Search", null, null, new { id = "lnkSearchMaster", #class = "btn btn-success", onclick = "return lnkgotoAction();" })
function lnkgotoAction() {
$('#grdSearchResults').show();
$('#searchdetails').show();
var rdVal = $("input[name = SearchType]:checked").attr("id");
if (rdVal == "CompanyList" || rdVal == "CompanyHistory" || rdVal == "ApplicationSatatus" || rdVal == "Certificates") {
$('#grdSearchResults').show();
var companyName = $('#companyname').val();
var status = $('#status').val();
var regNo = $('#registrationno').val();
var appRegNo = $('#applicationrefferenceno').val();
var url = '#Url.Content("~/")' + "Search/testFn?test='" + rdVal + "'&companyName='" + $('#companyname').val() +
"'®Num='" + $('#registrationno').val() + "'&appRegNum='" + $('#applicationrefferenceno').val() + "'";
alert(url);
}
$('#grdSearchResults').load(url + ' #grdSearchResults');
TempData.clear();
$('#grdSearchResults').show();
$('#searchdetails').show();
return false;
}
Controller:
public ActionResult testFn(string test, string companyName, string regNum, string appRegNum)
{}
Try as below, it will help you, also always take care the variable name passed to querystring must match controller action parameter names.
#Html.Raw(Url.Action("testFn", "Search"), new{ test= rdVal , companyName= companyName , regNum= regNo , appRegNum= appRegNo })
Related
I have an http-triggered azure function that receives a zip code. It then queries an Azure Table using the table API and retrieves the city, state, etc. The table contains zip/postal codes for US and CAN so there's about a million rows. When I send a request it returns the correct value the first time but if I keep sending it over and over it randomly switches between returning the record and returning an empty set. So it's not failing, and I'm not getting any kind of error like a timeout.
here is an example of a successful reply:
{
odata.metadata: "https://storageaccount###.table.core.windows.net/$metadata#Table###",
value: [
{
odata.etag: "W/"datetime'2019-10-18T16%3A02%3A26.9420514Z'"",
PartitionKey: "Portsmouth",
RowKey: "00210",
Timestamp: "2019-10-18T16:02:26.9420514Z",
AreaCode: "603",
City: "Portsmouth",
Country: "US",
Pref: "P",
State: "NH",
Zip: "00210"
}
]
}
and here is an empty one after pressing F5 after getting above reply:
{
odata.metadata: "https://storageaccount###.table.core.windows.net/$metadata#Table###",
value: [ ]
}
And then if I keep pressing F5 sometimes I get the record and sometimes I don't.
here are the table api url parameters (SAS-minus the signature)
?$filter=RowKey eq '00210' and Country eq 'US'
&sv=2019-02-02
&ss=t
&srt=sco
&sp=r
&se=2099-10-18T05:27:30Z
&st=2019-10-17T21:27:30Z
&spr=https
Does anyone know why it's behaving this way or what I could look into to figure it out?
According to this page there is a 5 second timeout for querying azure tables
(https://learn.microsoft.com/en-us/rest/api/storageservices/query-timeout-and-pagination). but when I look at the headers in postman I don't see any tokens.
postman results: https://i.stack.imgur.com/hReDM.png
full CORRECTED code
public static async Task<string> Run(HttpRequest req, ILogger log)
{
log.LogInformation("Start time = "+ DateTime.Now);
string apiResponse = "";
string zip = req.Query["zip"];
if(string.IsNullOrEmpty(zip)){return "No zip code found - please provide a url parameter in the format 'zip=[code]'";}
string apiBaseUrl = "https://***storage.table.core.windows.net/zip**?";
string queryFilter = "$first&$filter=RowKey eq '" + zip + "'";
//generate auth url in storage account in Azure
string authorization = "&sv=2019-02-02&ss=t&srt=sco&sp=r&se=2099-10-18T00:38:11Z&st=2019-10-17T16:38:11Z&spr=https&sig=7S%2BkaiTwGsZIkL***";
Regex rx_US = new Regex(#"^\d{5}$");
Regex rx_CA = new Regex(#"^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$");
if (rx_US.IsMatch(zip))
{
queryFilter = queryFilter + " and Country eq 'US'";
}
else if (rx_CA.IsMatch(zip))
{
//the table search is case sensitive - test for common errors
zip = zip.ToUpper(); //make all upper case
Regex rx_CA1 = new Regex(#"^[A-Z]\d[A-Z]-\d[A-Z]\d$"); //dash
Regex rx_CA2 = new Regex(#"^[A-Z]\d[A-Z]\d[A-Z]\d$"); //no space
if (rx_CA1.IsMatch(zip)){zip = zip.Replace("-", " ");}
if (rx_CA2.IsMatch(zip)){zip = zip.Insert (3, " ");}
queryFilter = "$single&$filter=RowKey eq '" + zip + "'" + " and Country eq 'CA'";
}
string queryUrl = apiBaseUrl + queryFilter + authorization;
try
{
var httpWebRequest = WebRequest.Create(queryUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Accept","application/json"); //if this is omitted you will get xml format
httpWebRequest.Method = "GET";
var httpResponse = await httpWebRequest.GetResponseAsync();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
apiResponse = responseText;
log.LogInformation("Full Table Response = " + responseText);
}
int i = 0;
while (httpResponse.Headers["x-ms-continuation-NextPartitionKey"] != null && apiResponse.Length < 105)
{
//if response is > 105 then it found something - don't keep looking
//if there are continuation tokens then keep querying until you find something
var partitionToken = httpResponse.Headers["x-ms-continuation-NextPartitionKey"];
var rowToken = httpResponse.Headers["x-ms-continuation-NextRowKey"];
var continuationUrl = "NextPartitionKey="+partitionToken+"&NextRowKey="+rowToken+"&";
queryUrl = apiBaseUrl + continuationUrl + queryFilter + authorization;
log.LogInformation("begin new httpRequest...");
httpWebRequest = WebRequest.Create(queryUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Accept","application/json");
httpWebRequest.Method = "GET";
httpResponse = await httpWebRequest.GetResponseAsync();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
apiResponse = responseText;
log.LogInformation("Full Table Response = " + responseText);
}
i++;
log.LogInformation("loop # "+ i + " - url = " + queryUrl + " Response = "+ apiResponse);
}
if(apiResponse.Length > 105)
{
//strip out extra data
apiResponse = apiResponse.Remove(1,101);
apiResponse = apiResponse.Remove(apiResponse.Length - 2,2);
}
else
{
apiResponse = "No data found for zip = " + zip + " - Ensure you have proper format and case";
}
}
catch (Exception ex)
{
apiResponse = "error: " + ex.Message;
}
log.LogInformation("ZipPostal function completed and returned "+ apiResponse);
return apiResponse;
}
We have an XPages application that is setup with help of Notes keyword documents. These keywords are made available via sessionScopes. An example of a scope variable is:
name scope: key_customer_sv
values:
default
values [Yes, No]
For the values I am using a LinkedHashSet to guarantee the insertion order:
var values:java.util.LinkedHashSet = new java.util.LinkedHashSet();
var iterator = keyValues.iterator();
while (iterator.hasNext()) {
var itemvalue = iterator.next();
values.add(itemvalue);
}
map.put("values",values);
The values are stored as as HashMap and the pair names are default and values.
For my xp:radioGroup control I want to read the scope variable and return the values of the value entry.
How must I do this?
Here is what I tried:
var language = "_" + context.getLocaleString();
var languageDefault = "_" + "sv";
var key = "customer";
var values;
try{
values = sessionScope.get("key_" + key + language )['values'];
}catch(e){
print(e);
}
if (null == values){
values = sessionScope.get("key_" + key + language Default)['values'];
}
return values
This works for me:
var language = "_" + context.getLocaleString();
var languageDefault = "_" + "sv";
var key = "customer";
var values;
try{
values = sessionScope.get("key_" + key + language ).get('values');
}catch(e){
print(e);
}
if (null == values){
values = sessionScope.get("key_" + key + languageDefault).get('values');
}
return values==null?"":values.toArray();
It is important by getting values using .get('values') instead of ['values'] , because it returns something different.
I tested is by filling sessionScope with this code:
var key_customer_sv:java.util.HashMap = new java.util.HashMap();
var values:java.util.LinkedHashSet = new java.util.LinkedHashSet();
values.add("Yes");
values.add("No");
key_customer_sv.put("values",values);
key_customer_sv.put("default", "Yes");
sessionScope.put("key_customer_sv", key_customer_sv)
I am working currently on a project that requires to send custom GET HTTP requests.
I am using the default querystring builder : the Documentation
const querystring = require('querystring');
The problem is for Object (probably also for empty array) such as
extendTypes={}
is serialiazed as :
extendTypes=
The expected result :
extendTypes={}
or its URI encoded version :
extendTypes%3D%7B%7D
So , how can I ever hope to do that ? If It is impossible with the in-builded module, which one could do what I want.
Here is my full code if you want :
function generateGetRequest(dataMap, url) {
let queryParams = {};
let uriParams = {};
for (let [key, value] of dataMap) {
// if value is an object or an array
if (value instanceof Object || value instanceof Array) {
uriParams[key] = value;
} else {
// param working for superagent
queryParams[key] = value;
}
}
let queryParamsUri = querystring.stringify(uriParams);
console.log(queryParamsUri);
let finalUrl = url + ( (Object.keys(uriParams).length > 0) ? "?" + queryParamsUri : "");
}
I finally found a workaround , if someone wants to know :
let request = require("superagent");
function generateGetRequest(dataMap, url) {
let queryParams = {};
let queryParamsUri = "";
let isFirstParam = true;
for (let [key, value] of dataMap) {
// if value is an object or an array
if (value instanceof Object) {
// Workaround for empty object or array = https://github.com/nodejs/node/issues/12234
queryParamsUri += ((!isFirstParam) ? "&": "") + key + "=" + JSON.stringify(value);
// for next call
isFirstParam = false;
} else {
// param working for superagent
queryParams[key] = value;
}
}
let finalUrl = url + ( (!isFirstParam) ? "?" + queryParamsUri : "");
return request
.get(finalUrl)
.query(queryParams);
}
The code below will get the URL variables..
For example: http://www.example.com/index.php?id=1&image=awesome.jpg
Calling getQueryVariable(“id”) – would return “1”
Calling getQueryVariable(“image”) – would return “awesome.jpg”
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
What if i want to return default value with the URL without query parameters? http://www.example.com/index.php
I still want to return “id” value = “predefined value"
You can do something like:
function getQueryVariable(variable)
{
default_values= {'id':-1,'image':'123.jpg'}
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(default_values[variable] || false);
}
Two suggestions:
1) set a default options object and return the desired value of that key if the url contains no parameters.
function getQueryVariable(variable)
{
var defaultValues = {
id: 'predefined valie',
image: 'defaultimage.jpg'
}
var query = window.location.search.substring(1);
var vars = query.split("&");
if (vars.length == 0) return defaultValues[variable] || false;
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
getQueryVariable('id'); //will return query parameter id or 'predefined value' if the url contains no parameters
2) or set the desired default value when calling the function.
function getQueryVariable(variable, defaultValue)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
if (vars.length == 0) return defaultValue || false;
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
getQueryVariable('id', 'predefined value'); //will return query parameter id or 'predefined value' if the url contains no parameters
getQueryVariable('image', 'defaultimage.jpg'); //will return query parameter image or 'defaultimage.jpg' if the url contains no parameters
I am getting an error after auto populating a Look-UP though javascript. My code is below. It is working and I am able to autopopulate. But when I click on the autopopulated filed I am getting an error. Also an error while saving the record.Errors are :
1) 'ryan_leadengagementprincipalassignment with id = ******* does not exist' (When I click on the populated Lookup value)
2) The requested record is not found or you do not have sufficient privilege to view it. (While saving the record)
Code:
var LEPAccountLookup= crmForm.all.customerid.DataValue;
if (LEPAccountLookup!= null && LEPAccountLookup!= 'undefined')
{
var LEPAccountID= LEPAccountLookup[0].id;
var LEPAccountxml = '' +
'<?xml version=\'1.0\' encoding=\'utf-8\'?>' +
'<soap:Envelope xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'>' +
GenerateAuthenticationHeader() +
' <soap:Body>' +
' <RetrieveMultiple xmlns=\'http://schemas.microsoft.com/crm/2007/WebServices\'>' +
' <query xmlns:q1=\'http://schemas.microsoft.com/crm/2006/Query\' xsi:type=\'q1:QueryExpression\'>' +
' <q1:EntityName>ryan_leadengagementprincipalassignment</q1:EntityName>' +
' <q1:ColumnSet xsi:type=\'q1:AllColumns\' />' +
' <q1:Distinct>false</q1:Distinct>' +
' <q1:Criteria>' +
' <q1:FilterOperator>And</q1:FilterOperator>' +
' <q1:Conditions>' +
' <q1:Condition>' +
' <q1:AttributeName>ryan_accountnameid</q1:AttributeName>' +
' <q1:Operator>Like</q1:Operator>' +
' <q1:Values>' +
' <q1:Value xsi:type=\'xsd:string\'>' + LEPAccountID + '</q1:Value>' +
' </q1:Values>' +
' </q1:Condition>' +
' </q1:Conditions>' +
' </q1:Criteria>' +
' </query>' +
' </RetrieveMultiple>' +
' </soap:Body>' +
'</soap:Envelope>' +
'';
//alert(LEPAccountxml);
var xmlHttpRequest = new ActiveXObject('Msxml2.XMLHTTP');
xmlHttpRequest.Open('POST', '/mscrmservices/2007/CrmService.asmx', false);
xmlHttpRequest.setRequestHeader('SOAPAction','http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple');
xmlHttpRequest.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xmlHttpRequest.setRequestHeader('Content-Length', LEPAccountxml.length);
xmlHttpRequest.send(LEPAccountxml);
var resultLEPAccountxml = xmlHttpRequest.responseXML;
//alert(resultLEPAccountxml);
//----------------------------------------------------------------------------------------------------------------------
var entityNodes = resultLEPAccountxml.selectNodes('//RetrieveMultipleResult/BusinessEntities/BusinessEntity');
for (var i = 0; i < entityNodes.length; i++) {
var entityNode = entityNodes[i];
var LEPAccountNode = entityNode.selectSingleNode("q1:ryan_accountnameid");
var LEPAccountNodename = entityNode.selectSingleNode('./q1:ryan_accountnameid/#name');
var LEPParentPracAreaNode = entityNode.selectSingleNode("q1:ryan_parentpracticeareaid");
var LEPParentPracAreaNodename = entityNode.selectSingleNode('./q1:ryan_parentpracticeareaid/#name');
var LEPPracAreaNode = entityNode.selectSingleNode("q1:ryan_practiceareaid");
var LEPPracAreaNodename = entityNode.selectSingleNode('./q1:ryan_practiceareaid/#name');
var LEPLegalEntityNode= entityNode.selectSingleNode("q1:ryan_legalid");
var LEPLegalEntityNodename = entityNode.selectSingleNode('./q1:ryan_legalid/#name');
var LEPNode= entityNode.selectSingleNode("q1:ryan_leadengagementid");
var LEPNodename = entityNode.selectSingleNode('./q1:ryan_leadengagementid/#name')
var LEPAccountid= (LEPAccountNode == null) ? null : LEPAccountNode.text;
var LEPAccountname= (LEPAccountNodename == null) ? null : LEPAccountNodename.text;
var LEPPareantPracAreaid= (LEPParentPracAreaNode == null) ? null : LEPParentPracAreaNode.text;
var LEPPareantPracAreaname= (LEPParentPracAreaNodename == null) ? null : LEPParentPracAreaNodename.text;
var LEPPracAreaid= (LEPPracAreaNode == null) ? null : LEPPracAreaNode.text;
var LEPPracAreaname= (LEPPracAreaNodename == null) ? null : LEPPracAreaNodename.text;
var LEPLegalEntityid= (LEPLegalEntityNode == null) ? null : LEPLegalEntityNode.text;
var LEPLegalEntityname= (LEPLegalEntityNodename == null) ? null : LEPLegalEntityNodename.text;
var LEPEntityid= (LEPNode == null) ? null : LEPNode.text;
var LEPEntityname= (LEPNodename == null) ? null : LEPNodename.text;
//alert(LEPAccountid);
//(LEPAccountname);
var LEPAccount = crmForm.all.customerid.DataValue;
var LEPLE = crmForm.all.ryan_ryanlegalentityid.DataValue;
var LEPPPA = crmForm.all.ryan_parentpracticearea2id.DataValue;
var LEPPA = crmForm.all.ryan_practiceareaid.DataValue;
if((LEPAccount != null) &&(LEPLE != null) && (LEPPPA != null) && (LEPPA != null))
{
if ((LEPAccountid== LEPAccount[0].id) && (LEPLegalEntityid== LEPLE[0].id) && (LEPPareantPracAreaid== LEPPPA[0].id) && (LEPPracAreaid== LEPPA[0].id))
{
var lookup = [];
var lookupValue = new Object();
lookupValue.id = LEPEntityid;
lookupValue.typename = 'ryan_leadengagementprincipalassignment';
lookupValue.name = LEPEntityname;
lookup[0] = lookupValue;
crmForm.all.ryan_leadengagementprincipalid.DataValue = lookup;
crmForm.all.ryan_leadengagementprincipalid.ForceSubmit = true;
}
}
}
}
There is likely something wrong with your SOAP call. When you debug it, does resultLEPAccountXml have an xml response string? or is it just returning an error/empty set? (it appears you were alerting that and have commented it out)
Unfortunately I'm not familiar enough with your particular data model to verify that you are querying for the same table that you are attempting to populate. Is the ryan_leadengagementid field on the ryan_leadengagementprincipalassignment table indeed the correct field to use to set the lookup on whatever form you are executing this script (ie is ryan_leadengagementprincipalid a lookup to the ryan_leadengagementprincipalassignment table)? If you are setting the lookup for the wrong table, then that will cause an issue that looks exactly like this.
Also (as a side note), it appears you are doing a RetrieveMultiple, and looping through and setting the target field multiple times potentially - is this the intended functionality (setting that lookup based on all the leadengagementprincipalassignment results)? The setting of the lookup field looks fine, so I suspect it is the code to retrieve the values which should be used to set the lookup that is the culprit here.