JQUERY call to Controller Action: String Parameter truncated if containing 'space' character - asp.net-mvc

I have a view that accepts 2 string parameters and 2 date values. User hits search button and they get filtered output to the screen. This all works perfectly well until a user inputs a string with a space. i.e. they can search for 'waste' but not 'waste oil'.
Interestingly, in the latter, the parameter is ok from Javascript before the call is made. But on entering the controller code it goes form being 'waste oil' on client to 'waste'. When this happens the other parameters get set to NULL crashing the system.
I've tried replacing the spaces if present with '#' character then stripping out and putting back in ' ' on the controller side. This is a messy fudge and only appears to work with one parameter.
There must be a simple explanation for this parameter data loss, any comments much appreciated
Not sure a code example is needed but here it is anyway if it help:
My controller header :
public ActionResult IndexSearch(int? page, string searchText,string searchTextSite,string StartDate,string EndDate)
{
My HTML Javascript :
function Search(sSearchText,sSite) {
sSearchText = sSearchText.toString().replace(" ", "#");
sSite = sSite.toString().replace(" ", "#");
debugger;
alert($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val());
$("#ResultsList").load($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val(),
function() {
$('#LoadingGif').empty();
});
$('#LoadingGif').empty().html('<img src="' + $("#AbsolutePath").val() + 'Content/images/ajax-loader.gif" alt="Loading image" />');
}

You are not URL encoding your parameters when sending the AJAX request because you are using string concatenations when building the url. You could use the following technique in order to have properly encoded values:
var url = $('#AbsolutePath').val() + 'Waste.mvc/IndexSearch';
var data = {
searchText: sSearchText,
searchTextSite: sSite ,
StartDate: $('#StartDate').val(),
EndDate: $('#EndDate').val()
};
$('#ResultsList').load(url, data, function() {
$('#LoadingGif').empty();
});
Now you will get correct values on the server.

Related

403 Invalid token error on GET user info

UPDATE: I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now.
I'm new to Valence. I have some Salesforce Apex code (written by someone else) that creates a D2L user. The code is working fine.
I want to add an Apex method to retrieve info for an existing D2L user using the userName parameter. I've copied the existing method, changed to a GET, set the query parameter to userName, and kept everything else the same.
When I call my method, I get a 403 Invalid Token error.
Do I need to use different authorization parameters for a GET? For example, do I still need to include a timestamp?
Here's a portion of the Salesforce Apex code:
public static final String USERS = '/d2l/api/lp/1.0/users/';
String TIMESTAMP_PARAM_VALUE = String.valueOf(Datetime.now().getTime()).substring(0,10);
String method = GETMETHOD;
String action = USERS;
String signData = method + '&' + action + '&' + TIMESTAMP_PARAM_VALUE;
String userSignature = sign(signData,USER_KEY);
String appSignature = sign(signData,APP_KEY);
String SIGNED_USER_PARAM_VALUE = userSignature;
String SIGNED_APP_PARAM_VALUE = appSignature;
String endPoint = DOMAIN + action + '?' +
APP_ID_PARAM + '=' + APP_ID + '&' +
USER_ID_PARAM + '=' + USER_ID + '&' +
SIGNED_USER_PARAM + '=' + SIGNED_USER_PARAM_VALUE + '&' +
SIGNED_APP_PARAM + '=' + SIGNED_APP_PARAM_VALUE + '&' +
TIMESTAMP_PARAM + '=' + TIMESTAMP_PARAM_VALUE;
HttpRequest req = new HttpRequest();
req.setMethod(method);
req.setTimeout(30000);
req.setEndpoint(endPoint);
req.setBody('{ "orgDefinedId"' + ':' + '"' + person.Id + '" }');
I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now

ModelState invalid in KendoUI date sent to ASP MVC

I'm using ASP MVC and KendoUI. Data are sent in json format. I'm getting ModelState error from KendoUI grid update where the according to debugger the ModelState ErrorMessage - "The value '/Date(1361499139623)/' is not valid for FirstAvailableDate."
Here's the print screen of my firebug POST
How to resolve this? I'm currently doing ModelState.Clear(); ...sad...
Most probably the project is missing the "kendo.aspnetmvc.min.js" script.
I ended up formating the date using javascript before posting it back to ASP MVC Controller.
Here's my javascript:
function toISOString(d) {
var year = d.getFullYear();
var month = d.getMonth() + 1;
var date = d.getDate();
return year + '-' + month + '-' + date;
}
function toMVCDateTime(d) {
return d.getUTCFullYear() + '-' + padzero(d.getUTCMonth() + 1) + '-' + padzero(d.getUTCDate()) + 'T' + padzero(d.getUTCHours()) + ':' + padzero(d.getUTCMinutes()) + ':' + padzero(d.getUTCSeconds()) + '.' + pad2zeros(d.getUTCMilliseconds()) + 'Z';
}
$.ajax({
url: "TimeSheet/GetWeeklyHistoricalTimeSheets",
type: "POST",
//data: { date: utcDate.toISOString() },
data: { date: toISOString(utcDate)},
success: function (response) {
htmlFactory(response);
}
});

how to read parameter with window.open in asp.net MVC3

I need to call an ASPX page from MVC view through below JavaScript code, also need to pass some parameter as query string,
function OpenTest() {
var width = (screen.availWidth - 700).toString();
var height = (screen.availHeight - 100).toString();
var param1 = "Test";
var baseUrl = '#Url.Content("~/Test/Test.aspx?")';
window.open(baseUrl + "param1=" + param1);
}
In ASPX page,
if(!string.IsNullOrWhiteSpace(Request.QueryString["param1"]))
{
string s1 = Request.QueryString["param1"];
}
I am able to call ASPX page and read parameter value by above code, but when I add other property of "window.open", I am not able to read query string, question is where should I place below property in above code so that I can also read query string value in ASPX page,
"mywindow", "width=" + width + ",height=" + height + ",toolbar=no,location=no,directories=yes,status=no," +
"menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes" + ",screenX=0,screenY=0,left=0,top=0"
The syntax for window.open() is:
window.open('url/for/page/here.aspx', 'targetName', 'options');
The targetName can be "_self", "_blank", "_parent", just like any target attribute for links, or have an identifier to name the window, so you can reuse the window when openning with the same name.
When you calll window.open() with any option to restrict the window, like width=100 it assumes that all the other have to be disabled, so you don't have to put the properties you want to disable.
Fixing your options would be:
window.open(baseUrl + "param1=" + param1,
"mywindow",
"width=" + width + ",height=" + height + ",directories=yes,scrollbars=yes,copyhistory=yes,resizable=yes,screenX=0,screenY=0,left=0,top=0");
Another thing to note is that all options have to be separated by comas, without spaces. Some browsers ignore/missinterpret options with spaces.
Also, don't forget to escape the variables to pass with the url.

jqGrid - How to put a specify page number

I want to make the following :
1. I have the following formatter function:
function ActionDescriptionFormatter(cellval, opts, rwdat, _act) {
var str = "<a border='0' style='text-decoration: none;' href='/Admin/IdeaDescription?id=" + cellval + "' title='Description'><img src='/images/aico_descr.png' alt='Description' border='0' /></a>";
return str;
}
I want to add also current pagenumber to url.
I want to set page of grid if It's passed via url
How to do it?

jQuery $.post - do I have to encode the URL parameter?

I'm making an AJAX call with $.post(url, cb). The URL I'm passing in could potentially have weird characters like spaces, &, ? and so on.
Do I have to use $.post(encodeURIComponent(url), cb)?
url is something like /foo/weird-char§.
Do I have to use $.post(encodeURIComponent(url), cb)?
You will have to use encodeURIComponent() but not on the entire URI, only on the data part (weird and chars in your example). The URL and the ? & separating the parameters must stay intact. If you encode the entire URI, it will become unusable.
If you would add the data as POST data using the data parameter:
url = "/foo/possible";
$.post(url, { "weird": "f2(90§§$", "chars": "ß1028490" });
jQuery's Ajax functions would take care of URL encoding the data automatically.
Yes, you would need to encode the keys and values in the query string (but not the ? which separates the path from the query arguments and the & which separates the query arguments). This is built into jQuery if you use the data parameter of the $.post, like so:
$.post(url, { name: "John", time: "2pm" }, cb);
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});

Resources