javascript Request.QueryString - c#

How do I request querystring using javascript from URL
e.g : http://localhost:1247/portal/alias__MySite/lang__en/tabid__3381/default.aspx
I want to get tabid...
var tabid = '<%= Request.QueryString["tabid"] %> ';
Above code works only in aspx page
but i dont need it, any ideas? thanks

There is now a new api URLSearchParams. Use that in conjunction with window.location.search
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get('tabid'));
If your browser does not support URLSearchParams, you can create a custom fallback function:
function getParam(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
console.log(getParam('tabid'));

Don't know why but I've always found the javascript for querystring data fetching a bit hacky. if you don't need this value on the initial page load then perhaps you could use Request.QueryString in the code and set the value to a hidden field, which your javascript will read from?

Try this, It is working perfectly for me.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var tabId=getParameterByName("tabid");

I bet there is a server-side rewrite (DotNetNuke?), so the aspx.cs "sees" the redirection target which contains the correct QueryString.
For the client, you have to use another mechanism because the browser only "sees" the public URL. In this case, a Regex that picks the number behind 'tabid_' and before the next slash should work. This would be the same number (page id?) that the aspx page "sees".

This is what I used:
<script type="text/javascript">
function QueryString(key) {
//Get the full querystring
fullQs = window.location.search.substring(1);
//Break it down into an array of name-value pairs
qsParamsArray = fullQs.split("&");
//Loop through each name-value pair and
//return value in there is a match for the given key
for (i=0;i<qsParamsArray.length;i++) {
strKey = qsParamsArray[i].split("=");
if (strKey[0] == key) {
return strKey[1];
}
}
}
//Test the output (Add ?fname=Cheese&lname=Pizza to your URL)
//You can change the variable to whatever it is you need to do for example, you could
//change firstname to id and lastname to userid and just change the reference in the
//document.write/alert box
var firstname = QueryString("fname");
var lastname = QueryString("lname");
document.write("You are now logged in as " + firstname + " " + lastname + "!");
</script>
You can replace document.write with alert and it would give you an alert box instead!
I used this on my website. Its not done yet but when it is it will be at zducttapestuff.com
The output will look like this: You are now logged in as Cheese Pizza!
This is very unsecure for Passwords though since the password will be shown in the url.

Related

C# get parameter from url after redirect

I have a redirect:
string linkedInLogin = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=ID&redirect_uri=https%3A%2F%2Fwww.example.com%2Fauth%2Flinkedin&state=ZEKNI&scope=r_basicprofile";
Response.Redirect(linkedInLogin);
This results in a redirect in my browser to
https://www.example.com/auth/linkedin?code=CODE_I_NEED&state=STATE
How do I retrieve the value of the code paramater?
Request.Querystring["code"] gives me a null value. The problem is that the browser "thinks" the current URL was /home/MyController.
try:
HttpContext.Current.Request.Params["code"]
this way you can get a combined collection of QueryString, Form, Cookies, and ServerVariables items.
here you can read more: HttpRequest.Params Property
Do you have that link stored somewhere or are you asking for how to retrieve it as well?
Assuming you already have it:
var s = "https://www.example.com/auth/linkedin?
code=CODE_I_NEED&state=ROB962242SMUT"
You can either do:
string s = "https://www.example.com/auth/linkedin?code=CODE_I_NEED&state=ROB962242SMUT";
var code = s.Substring((s.IndexOf("code=") + 5), (s.IndexOf('&') - (s.IndexOf("code=") + 5)));
//CODE_I_NEED
Or
String sourcestring = "https://www.example.com/auth/linkedin?
code=CODE_I_NEED&state=ROB962242SMUT";
Regex re = new Regex(#"code=(.*)&");
var result =Match m = re.Match(sourcestring).Value;
//CODE_I_NEED
edit: based on the other two answers i may not have understood your question properly xd

RouteUrl replace "&" with "&" in query string parameters

I have the following code:
#Url.RouteUrl("NewMessage", new { parentThreadId = Model.thread.id, cacheBustParam = currentUserId })
When the page get rendered the page source looks like:
/somepath/newMessage/12345?cacheBustParam=123&param1=value1&param2=value2
As you can see instead of plain ampesands & it places & in the query string params and that makes them unusable.
How can i instruct the #Url.RouteUrl not to encode the querystring?
Try using
#Html.Raw(Url.RouteUrl("NewMessage", new { parentThreadId = Model.thread.id, cacheBustParam = currentUserId }))

How to rename element ids to conform to model sequence collection

C# MVC web application
I have a button that adds input fields dynamically to my web page on a form.
I specifically give the dynamically added elements an id and name to conform to my Model so that they get passed back as an collection of like items to match a “Artists” collection property in my model.
So the input elements name and ids are for example
Artists[0].artist
Artists[1].artist
Artists[2].artist
In my model I have:
public Collection<Artist> Artists { get; set; }
public class Artist
{
public string artist { get; set; }
}
And here is my script to add remove an element:
var artists = new Array();
var AddArtist = function (e) {
artistname = $("#artistinput").val();
artists.push($("#artistinput").val());
var addDiv, artistVal;
addDiv = $("#artist");
artistVal = $("#artistinput").val();
var input_append = $('<div />'),
label = $('<input />', {
style: 'background-color:#e0ffff',
Value: artistVal,
id: 'artists[' + (artists.length - 1) + '].artist',
name: 'artists[' + (artists.length - 1) + '].artist',
readonly: true
}),
image = $('<img />', {
id: 'removeartist',
src: '/Content/bootstrap/img/cross-button.png',
on: {
click: function () {
input_append.remove();
artists.splice(artists.length - 1, 1);
var test = (artists.length - 1);
alert(test);
}
}
}
);
addDiv.append(input_append.append(label, image));
};
I can add/remove the elements on the actual page. The problem is, if I remove an element from the middle or beginning, the sequence of the name ids are broken and when the collection get passed back to my model the Artists collection is now empty.
So instead of
Artists[0].artist
Artists[1].artist
Artists[2].artist
This may be passed back:
Artists[0].artist
Artists[2].artist
Which is no longer a collection based on how the view is mapped to the model.
I need to rename all the name/ids in a ordered sequence once an item has been removed.
What’s the easiest solution for this problem.
So that this gets passed back
Artists[0].artist
Artists[1].artist
Okay here's what I used in a previous project to revise the IDs and names of inputs to allow model binding when posted to an MVC controller.
The first function takes an object and searches for all inputs, selects and textareas contained within it. The object you pass would probably be a row or div that contains all related inputs per Artist.
// Applies new id and name with correct number sequence to set fields
function reviseFieldNameAndId(obj, newNumber) {
obj.find('input,select,textarea').each(function () {
var parts = this.id.split(/_[\d+]__/); // Everything can be obtained from id only
this.id = parts[0] + '_' + newNumber+ '__' + parts[1]; // Payments_0__PaymentReasonId
this.name = parts[0] + '[' + newNumber+ '].' + parts[1]; // eg. Payments[0].PaymentReasonId
});
}
function reviseAllFieldNamesAndIds() {
$('#artists .row').each(function (index) {
reviseFieldNameAndId($(this), index);
});
}
Use the second function to go through all rows and perform the apply the new sequence.
PS - your answer is near enough the same as this but only works with artists whereas mine will work with different names and ids
I gave each dynamically added input item the same class name then used JavaScript to update and reorder every element id and name in an ordered sequence:
$('.divArtist').each(function (i, obj) {
this.id = 'artists[' + i + '].artist';
this.name = 'artists[' + i + '].artist';
});

Asp.net adding parameter to url string

I'm displaying a list of filtered items in a page, and now I have to limit the displaying by paginating the results.
So if I have url parameters like these:
example.com/?category=pizza&period=today
where both category and period can also not being showed:
example.com/?period=today
example.com/
how can I add a "Next page" in the end that keeps any previous parameter and adds
&pagenum=5
or if there are no parameters:
?pagenum=5
Tnx in advance!
For serverside
string url = Request.Url.GetLeftPart(UriPartial.Path);
url += (Request.QueryString.ToString() == "" ) ? "?pagenum=1" : "?" + Request.QueryString.ToString() + "&pagenum=1";
You can pass in the page number depending on how you are handling this.
For ASP.Net use the following:
string temp = Request.QueryString["yourParamName"];
Fissh

handle multiple controls with same name in form collection

I have a form in my asp.net mvc(C#) application which handles some dynamic controls.
On a button click "Add Row", i will add a row dynamically to the existing table as:
$('#btnAddMore').click(function() {
var _userBodyHtml = '';
_userBodyHtml += '<tr><td><input type="text" name="UserName" id="UserName' + _userDynId + '" size="10" /></td>';
_userBodyHtml += '<td><textarea name="UserComments" id="UserComments' + _userDynId + '" cols="60" rows="1"></textarea></td>';
_userBodyHtml += '</tr>';
_userDynId += 1;
$('#UserBody').append(_userBodyHtml);
});
Then the admin adds the username and comments and submits it.
On submit, i am handling it in controller's action as:
var _frmUserNames = new List<String>(form["UserName"].ToString().Split(','));
var _frmUserComments = new List<String>(form["UserComments"].ToString().Split(','));
if (_frmUserNames.Count > 0 && _frmUserComments.Count > 0)
{
List<UserComments> _userComments = Enumerable.Range(0, _frmUserNames.Count)
.Select(i => new UserComments
{
UserName = _frmUserNames[i],
UserComment = _frmUserComments[i]
}).ToList();
}
From the above code, the _frmUserComments returns the comma separated value when there are more than one textbox with the same name as i am differentiating the textboxes only with different ids.
The problem is when the admin enters the usercomments which has a comma(,) within that comment, then the form value _frmUserComments has the comma separated value and it gives invalid data to the List.
When Admin enters(Case 1) which is fine:
Sam Logged on 12/10/2010
David Looking for enhancement
the form values returns:
_frmUserNames = "Sam,David"
_frmUserComments = "Logged on 12/10/2010,Looking for enhancement"
When Admin enters(Case 2) which is problem causing:
Sam Logged on 12/10/2010
David Logged on 03/01/2011, Looking for enhancement
the form values returns:
_frmUserNames = "Sam,David"
_frmUserComments = "Logged on 12/10/2010,Logged on 03/01/2011, Looking for enhancement"
How can i handle the scenario like this.
Looks like you want to bind collection to model. I recommend to do it as Phil Haack does
Try to set dynamic controls name attributes same as IDs (with index - yours's _userDynId). You'll be able to iterate through form collection in controller, something like that (using LINQ):
foreach (var key in form.AllKeys.Where(k => k.StartsWith("UserName")))
{
var index = key.Replace("UserName", "");
var userName = form[key];
var userComment = form["UserComments" + index];
}

Categories

Resources