Create Cookie in Controller, read cookie from Javascript - javascript

using MVC.
In one of my controllers I am creating a cookie like the following:
Function Login(ByVal access_token As String) As ActionResult
Response.Cookies.Add(New HttpCookie("access_token", access_token))
End Function
I want to check the value of the cookie called "access_token" client-side, in order to know the next step to take in javascript.
How can I do that?
Any help would be appreciated
UPDATE
I found the solution:
I just add this function in Javascript :
function ReadCookie(cookieName) {
var theCookie = "" + document.cookie;
var ind = theCookie.indexOf(cookieName);
if (ind == -1 || cookieName == "") return "";
var ind1 = theCookie.indexOf(';', ind);
if (ind1 == -1) ind1 = theCookie.length;
return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}
and I call it on Document.ready() with the name of the cookie that I want to retrieve like that:
if (ReadCookie("access_token") != '')
{ }

Related

Adding a parameter to an extended url with jQuery?

I'm using a script to add parameters to a URL to use with a if statement for a layout change. It works with a structure like this:
/Computers/Desktops
on click to change layout:
/Computers/Desktops?param=list
and
/Computers/Desktops?param=grid
I'm using a filer that adds parameter, then the layout will change between something like this:
/Computers/Desktops?param=list&fss=HP+2GB
and on click:
/Computers/Desktops?param=grid&fss=HP+2GB
This works well, but I need to make this work for another structure that looks like this:
/Computers/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?prodid=30811
Here I want to add the parameter before ?prodid=30811 so the layout changes on click between
/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?param=list&prodid=30811
/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?param=grid&prodid=30811
I hoped I just could change FSS in my script to prodid, but this doesn't work. So why doesn't it work and why, and how do I do this instead? My if/else script already works, I just need the correct URL from the buttonclick.
$('.click3').on('click', function() {
console.log("Clicked");
var baseUrl = window.location.href.split("?")[0];
var fss = getParametersByName("fss");
var params = getParametersByName("fss");
if (params == "list")
param = "grid";
else
param = "list";
var newUrl = baseUrl + "?param=" + param;
if ((fss).length > 0)
newUrl = newUrl + "&fss=" + fss;
window.location.href = newUrl;
function getParametersByName(name) {
name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
});

Is withParameters still supported in Breeze entity query?

I tried to use withParameters method on query like that:
query.withParameters({ includeLocation: true })
Unfortunately my parameter was not added to url. I use breeze.debug.js and I've found this line in it
//queryOptions = __extend(queryOptions, this.parameters);
Is that a bug ? Is withParameters support taken out ? Or do I do something wrong ?
I use oData
When .withParameters is used, the parameters are added to the URL by the data service adapter, not by the Breeze core. That's why that line is commented out. This allows the parameters to be encoded differently, depending upon the backend that is used.
That's great, but the data service adapter for OData that ships with Breeze 1.4.8 does not handle .withParameters. The WebApi adapter does, but not the OData adapter. We'll make sure it's added in a future release. In the meantime, you can continue to use your workaround.
This oversight/omission is partly because we don't know any OData services that handle custom parameters. If I may ask, what OData service are you using?
It looks like this will hopefully be fixed soon: https://github.com/Breeze/breeze.js/issues/19.
In the meantime, you can use this code as a workaround (kudos to the author of this pull request):
var odataAdapter = breeze.config.getAdapterInstance('uriBuilder', 'OData');
var origBuildUri = odataAdapter.buildUri;
odataAdapter.buildUri = function (entityQuery, metadataStore) {
var uri = origBuildUri(entityQuery, metadataStore);
//Add custom query option support to webapi odata.
//See https://github.com/Breeze/breeze.js/issues/19
if (entityQuery.parameters !== null && typeof entityQuery.parameters === 'object'
&& Object.keys(entityQuery.parameters).length)
{
var queryParams = {};
for (var param in entityQuery.parameters) {
if (/^([^\$].*)$/.test(param)) {
var val = entityQuery.parameters[param];
if (typeof val == 'string') val = "'" + val + "'";
queryParams[param] = val;
}
}
//get the uri without the resourceName
var resourceName = entityQuery.resourceName;
uri = uri.substr(resourceName.length + 1);
//build the new uri
uri = resourceName + toQueryOptionsString(queryParams) + '&' + uri;
}
//Copied from breeze.js OData adapter
function toQueryOptionsString(queryOptions) {
var qoStrings = [];
for (var qoName in queryOptions) {
var qoValue = queryOptions[qoName];
if (qoValue !== undefined) {
if (qoValue instanceof Array) {
qoValue.forEach(function (qov) {
qoStrings.push(qoName + "=" + encodeURIComponent(qov));
});
} else {
qoStrings.push(qoName + "=" + encodeURIComponent(qoValue));
}
}
}
if (qoStrings.length > 0) {
return "?" + qoStrings.join("&");
} else {
return "";
}
}
return uri;
};

how to access json data globaly

In code below I am trying to retrieve clients machine IP. The problem is in TestIP variable this one shows null when I debug script. How I could assign this value to show clear string with IP after exiting from $.getJSON() function.
<script>
var test1 = null;
$(document).ready(function () {
var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
})
if (inDesignMode != "1") {
//should show IP - is Null
var TestIP = test1;
//Not getting the value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
});
Thanks in advance
The problem is that getJSON is an asynchronous call, so your subsequent if block is actually called before getJSON returns. You should move the if block inside the getJSON callback:
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
if (inDesignMode != "1") {
//should show IP
var TestIP = test1;
//Getting value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
})
Use your code in the getJSON callback like,
var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
// use you code here in callback function
if (inDesignMode != "1") {
//should show IP
var TestIP = test1;
//Getting value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
})
Put the if statement inside the $.getJSON call at the end of the lines you currently have in it. The problem is that $.getJSON is asynchronous and so its not necessarily done by the time you are trying to access test1
So what you want is:
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function (data) {
//getting IP correctly
test1 = data.host;
$('#' + '<%=hdnDeliServerGIP.ClientID%>').val(data.host);
if (inDesignMode != "1") {
//should show IP - is Null
var TestIP = test1;
//Not getting the value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
})
In order to make a global variable in javascript, we need to declare variable without using "var" keyword.
try using "test1 = null;"
in order to make a js variable globally you need to first declare a variable and then assign you json data onto that, and then you can access that variable globally.
eg:
$(document).ready(function () {
var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
$.ajax({
url :'http://smart-ip.net/geoip-json?callback=?',
async:false,
dataType:"json",
success: function (data) {
//getting IP correctly
test = data.host;
}});
if (inDesignMode != "1") {
//should show IP - is Null
var TestIP = test1;
//Not getting the value from hidden asp object
var GIP = $('#' + '<%=hiddenElementIP.ClientID%>').val() != '' ? $('#' + '<%=hdnDeliServerGIP.ClientID%>').val() : 'not set';
}
});
Note:- Please define test variable once outside this call in the begining of page
hope this will help you :)

Using javascript to check true/false condition on viewmodel

I am using local storage variable to hold the location of a users current progress. I have ran into a problem whereby if the last section that the user was on has been since deleted I am getting a target invocation must be set error. This is my code:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
I need to check using javascript that the localStorage course section is still existing in the database so I created the following ViewModel method:
public bool CourseSectionLaunchStillExistCheck(int courseSectionID)
{
this.TargetCourseSection = courseSectionRepository.Get(cs => cs.CourseSectionID == courseSectionID).FirstOrDefault();
if (this.TargetCourseSection != null)
{
return true;
}
else
{
return false;
}
}
But when I try to use the following javascript:
if (localStorage["Course" + '#Model.Course.CourseID'] != null && localStorage["Course" + '#Model.Course.CourseID'] != "") {
var id = localStorage["Course" + '#Model.Course.CourseID'];
if ('#Model.CourseSectionLaunchStillExistCheck(id)' != true) {
var id = '#Model.CourseSections.First().CourseSectionID';
}
}
else {
var id = '#Model.CourseSections.First().CourseSectionID';
}
It is failing to recognise the id parameter saying it does not exist in the current context. How can I ensure that the course section exists using javascript before setting the variable?
Could I use a post such as:
var postData = { 'courseSectionID': id };
$.post('/Course/CourseSectionLaunchStillExistCheck/', postData, function (data) {
});
and then how could i check if the result of this post data would be true or false?

MVC 4 Pass value from Javascript to Controller

In my view, I have a javascript function to handle a select event on a pie chart. The function is shown below:
function selectHandler() {
var selectedItem = visualization.getSelection()[0];
if (selectedItem) {
var val = data.getFormattedValue(selectedItem.row, 0);
location.href = '/Tickets';
}
}
Currently I am on the Home Controller in the Groups View. I want to navigate to the Index View of the Tickets Controller while passing the selected value from the javascript variable "val". How would I go about doing this?
Are you intending to manually navigate the user?
If you're looking for a redirect JavaScript way, then you would do something as simple as...
location.href = '/Tickets?value=' + val;
Now this may not work for everything. For example, if location.href already contains a '?', and you need to maintain that context, then you need to use '&'. Maybe your app lives in a Virtual Directory.
You might do something like...
var newUrl = location.href;
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
newUrl += val;
This allows you maintain any existing context as well.
If you expect the ticket to already be defined, you might need to remove that from the query string, if it already exists.
In that case then you might want to do something like...
var params = location.search.substring(1).split('&'),
paramToRemove, indexOfValue,
hasSearch = false,
param;
for (var i = 0, len = i; i < len; i++)
{
param = params[i];
indexOfValue = param.indexOf('value');
hasSearch = param.indexOf('?') === 0;
if (indexOfValue === 0 || (indexOfValue === 1 && hasSearch ))
{
paramToRemove = params[i];
break;
}
}
var newUrl = location.href;
// Remove old value
if (paramToRemove) newUrl = newUrl.replace(paramToRemove, hasSearch ? '?' : '');
// Add proper search char
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
// Add new value
newUrl += val;
location.href = '/Tickets?val=' + val;
//On page load the server will generate the URL for you.
var ticketURL = '#Url.Action("Index", "Tickets")';
//Append the value to the URL
ticketURL = ticketURL + '?val=' + val;
//Do your stuff!
Since, you are calling Controller methods from javascript. You should make an POST ajax call to Ticket Controller and passing Action method name also.
Your code would be like this:
return $.post('/Ticket(ControllerName)/Index(method name)/',parameters here);
Inside API Controller, Index method will accept the same param which we are passing from our javascript.
ActionResult Index(parameter){...}

Categories