angularjs get paramater from url - asp.net

i'm currently working on a asp.net mvc site in which we are using angularjs for model binding. i have a controller setup but i need to grab the id from the url to pass it to the service. my url looks like:
http://localhost/myapp/section/5
I need to grab the 5 out of the url, we are not using angular for routing, is there anyway to grab that through angular? Otherwise i could use .net to inject that into a global js variable and use angular to read the id from there.
I setup my angular controller as below:
myModule.controller('SectionController', ['$scope', 'sectionRepository', '$routeParams', SectionController]);
function SectionController($scope, sectionRepository, $routeParams) {
var vm = this;
alert($routeParams.id);
the alert returns 'undefined', I'm assuming because I never setup the routes in angular, is there a way to do it without the setup of routes, as we don't want to use angular for routing.

You can use the $location service to grab the URL. From there, just parse it.
function SectionController($location) {
var url = $location.url();
//regex is slow, you should use substring/slice instead
//var regex = /(?:section\/)[0-9]+/;
var id = url.substring(url.indexOf("section/") + "section/".length);
alert(id);
}

Related

How to send a POST request from GTM custom tag template?

I'm developing a simple custom tag template for Google Tag Manager. It's supposed to bind to some events and send event data to our servers as JSON in the body of a POST request.
The sandboxed GTM Javascript runtime provides the sendPixel() API. However, that only provides GET requests.
How one sends a POST request from within this sandboxed runtime?
You can use a combination of the injectScript and copyFromWindow APIs found here Custom Template APIs.
Basically, the workflow goes like this.
Build a simple script that contains a function attached to the window object that sends a normal XHR post request. The script I made and use can be found here: https://storage.googleapis.com/common-scripts/basicMethods.js
Upload that script somewhere publically accessible so you can import it into your template.
Use the injectScript API to add the script to your custom template.
The injectScript API wants you to provide an onSuccess callback function. Within that function, use the copyWindow api to grab the post request function you created in your script and save it as a variable.
You can now use that variable to send a post request the same way you would use a normal JS function.
The script I included above also includes JSON encode and Base64 encode functions which you can use the same way via the copyWindow api.
I hope that helps. If you need some specific code examples for parts I can help.
According to #Ian Mitchell answer - I've made similar solution.
This is the basic code pattern that can be used inside GTM template code section in such as scenario:
const injectScript = require('injectScript');
const callInWindow = require('callInWindow');
const log = require('logToConsole');
const queryPermission = require('queryPermission');
const postScriptUrl = 'https://myPostScriptUrl'; //provide your script url
const endpoint = 'https://myEndpoint'; //provide your endpoint url
//provide your data; data object contains all properties from fields tab of the GTM template
const data = {
sessionId: data.sessionId,
name: data.name,
description: data.description
};
//add appropriate permission to inject script from 'https://myPostScriptUrl' url in GTM template's privileges tab
if (queryPermission('inject_script', postScriptUrl)) {
injectScript(postScriptUrl, onSuccess, data.gtmOnFailure, postScriptUrl);
} else {
log('postScriptUrl: Script load failed due to permissions mismatch.');
data.gtmOnFailure();
}
function onSuccess() {
//add appropriate permission to call `sendData` variable in GTM template's privileges tab
callInWindow('sendData', gtmData, endpoint);
data.gtmOnSuccess();
}
It's important to remember to add all necessary privillages inside GTM template. Appropriate permissions will show automatically in privillages tab after use pertinent options inside code section.
Your script at 'https://myPostScriptUrl' may looks like this:
function sendData(data, endpoint) {
var xhr = new XMLHttpRequest();
var stringifiedData = JSON.stringify(data);
xhr.open('POST', endpoint);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(stringifiedData);
xhr.onload = function () {
if (xhr.status.toString()[0] !== '2') {
console.error(xhr.status + '> ' + xhr.statusText);
}
};
}
It is not strictly necessary to load an external script. While still a workaround, you can also pass a fetch reference into the tag through a "JavaScript Variable" type variable:
Create a GTM variable of type "JavaScript Variable" with the content "fetch", thus referencing "window.fetch"
Add a text field to your Custom Tag, e. g. named "js.fetchReference".
Use data.fetchReference in your Custom Tag's like you normally would use window.fetch
Make sure the tag instance actually references the variable created in step 2 with {{js.fetchReference}}
I jotted this down with screenshots at https://hume.dev/articles/post-request-custom-template/

Create a url that passes values to controller action

I want to create a Url that I can email that goes to an action within a controller, passing to the action an Id and a Token. This is my code so far:
var action = new UrlActionContext
{
Action = "Verify",
Controller = "Auth",
Values = id, token
};
var url = UrlHelperExtensions.Action(action);
UrlHelperExtensions.Action is expecting an IUrlHelper however, and I have not been able to get this to work using that interface. Can someone please explain how I am able to form a Url that goes to this action?
I can only seem to find solutions to Asp.Net MVC projects, whereas I am using Asp.Net Core 2.0.
For ASP.Net Core 2.0 IUrlHelper is available as a property of the controller. ControllerBase.Url is an IUrlHelper instance. You should be using it like this:
var url = Url.Action(nameof(DoSomething), new { id = 10 });

Adding custom data in App insights page level tracking

I'm using App insights in my ASP.NET MVC Angular application. I've inserted the JavaScript block (that I got from the Microsoft site) in my layout file in order to track the page level telemetry. I would like to add custom data (username that is in my session variable) to this telemetry. How can I do this?
For server side I know I can add custom data by using initializers, but I don't know how to do it from JavaScript.
appInsights.trackPageView
(
"page name",
"http://domain.com/pageurl.html",
{
PropertyA: object.propertyA,
PropertyB: object.propertyB
}
);
For more information: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics#a-namepropertiesafilter-search-and-segment-your-data-with-properties
the AI JavaScript SDK has very similar concepts. In this case, you probably want a javascript telemetry initializer:
from https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-filtering-sampling
(and also https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md)
// Adding telemetry initializer.
// This is called whenever a new telemetry item
// is created.
appInsights.queue.push(function () {
appInsights.context.addTelemetryInitializer(function (envelope) {
var telemetryItem = envelope.data.baseData;
// To set custom properties:
telemetryItem.properties = telemetryItem.properties || {};
telemetryItem.properties["globalProperty"] = "boo";
// To set custom metrics:
telemetryItem.measurements = telemetryItem.measurements || {};
telemetryItem.measurements["globalMetric"] = 100;
});
});
and inside that telemetry initializer you'd set whatever values you want.
if it is user info, you can also use setAuthenticatedUserContext instead of a telemetry initializer.

Injecting precompiled handlebars template in Handlebars.template method

Hi I am currently using Express Handlebars setup [https://github.com/ericf/express-handlebars][1] to render compiled and pre-compiled templates. In case of pre-compilation I have configured express middleware to get handlebars templates as precompiled and manually configured registration of handlebars pre-compiled templates like this:
hbs.getTemplates('views/partials/page/', {
cache : app.enabled('view cache'),
precompiled: true
}).then(function (templates) {
var templatesArr = hbs.handlebars.templates = hbs.handlebars.templates || {}
// extract all templates names and values
templates = Object.keys(hbs.handlebars.templates).map(function (name) {
//get precompiled template data
var templateSpec = templates[name]
//Inject precompiled data into Handlebars.template method
var precompileTemplateRef = hbs.handlebars.template(templateSpec)
//templateSpec is treated as String rather than Object
//and this is where the things break because
//handlebars.template expects Object
//Register precompileTemplateRef with Handlebars so that
//precompiled template can be extracted for later use by using
//template name
templatesArr[name] = precompileTemplateRef
});
When I run the express server, hbs.handlebars.template doesn't get executed because templateSpec mentioned above is received as a string rather than object.
Even using JSON.parse(templateSpec) doesn't work because precompiled output is not JSON BUT an Object literal.
Precompiled output looks something like this:
{"1":function(container,depth0,helpers,partials,data) {var helper;ret.......
I want to know if its possible to inject just the pre-compiled output at run time into Handlebars.template(templateSpec) OR Do I have to create precompiled template in file system which has registration with Handlebars.templates.
In case of compiled templates there are no issues.
Many thanks in advance
This is an open issue with Handlebars as per the following links:
https://github.com/wycats/handlebars.js/issues/922
https://github.com/wycats/handlebars.js/issues/1033
var templateSpec = (new Function('return ' + templates[name])());
Will resolve the problem

ASP.NET 4.0 URL routing with two or multiple querystring parameters

How can I pass two querysting parameters in URL routing using ASP.NET 4.0?
I have gone through many articles, but everywhere it shows only one parameter.
I'd like the display URL to be:
http://www.mywebsite.com/reports/1-this-is-my-first-report
The first parameter is ID: 1
The second is Name: This is my first report
I am trying following route, but it is not working
routes.MapPageRoute(
"MarketReports", // Route name
"Reports/{*i}-{*n}", // Route URL
"~/pageControl2.aspx" // Web page to handle route
);
How can I make this work as described?
Try formatting the URL this way:
http://www.mywebsite.com/reports/1/this-is-my-first-report
routes.MapPageRoute(
"MarketReports", // Route name
"Reports/{*i}/{*n}", // Route URL
"~/pageControl2.aspx" // Web page to handle route
);
Try this
Response.RedirectToRoute("UrlRouting for Querystring",
new { name = txtsearchurlrouting.Text, text = txtsearchid.Text });
In Global.asax
routes.MapPageRoute("UrlRouting for Querystring",
"Querystring/Selected/{name}/{text}/", "~/Address.aspx");
like this we can pass multiple querystring parameters

Resources