Take C# const from backend and use it in JS file? - javascript

I have one tricky question.
Is there a way to take C# const and use it in .JS script with Jquery ?
This is how const look:
public class UserRoles
{
public const string Read = "Read";
public const string ReadWrite = "ReadWrite";
}

It depends a bit of what you are trying to do with those values.
You could place the values in a js object when your UI initializes (ex: window.YourAppName.Constants.Read = "your C# constant" in Index.html). Then you could load your jquery script and make use of the constant values once the document finished loading.
Alternatively, if you are using MVC, you can make use of tags within your views, and thus have access to C# code (viewmodel, enums, etc.). However, if you have lots of js code then it would be best to keep that in js files and in such a case I would go for the first option.

You can't use Razor in JavaScript files, you would have to have the variable passed to a razor view in the viewbag/data or model.
Then in the shared layout you could create a javascript function that returns this variable, then in your .JS file you could call that function to get the variable as long as it is loaded after.

Related

Passing Object from ASP.Net to javascript

I have an ASP.Net Core application. I have a Class with some attributes:
public class myClass
{
public string name {get; set;}
public int id{get; set;}
...
}
and in PageModel of Index.cshtml, I am creating on object of that class and setting it is a property:
public class IndexModel : PageModel
{
public myObj data { get; set; }
public void OnGet(int inputId)
{
data = new myClass();
data.name = "name";
data.id = inputId;
}
}
Now, in my Index.cshtml, I have some default html and then I add a script like this:
<script type="module" src="~/built/script.js"></script>
Finally, my question: I need the data that I have defined in IndexModel in my script.js. In a normal cshtml-page, I would do #Model.data, but that decorator is not available in my js file. Is there a way to do this, or should I use one of the following which I think might work:
Adding an API-controller in ASP.Net and calling it in my script.js with ajax: I think this should work, but it seems to me like I am supposed to do it with #Model instead
Somehow storing it in a global variable in my .cshtml file and then accessing that global variable in script.js: Seems like a hack
I'm pretty new to ASP.Net and JS, so there might be an obvious answer to this that I'm just too inexperienced to know. Any help is appreciated!
You could use model binding as intended and convert the model to a javascript variable at the top of your view, then it will be available in the script file as a javascript variable as long as you load the javascript file after you create the variable to hold your model.
---YOUR VIEW---
#model YourModel
#using Newtonsoft.Json;
<script type="text/javascript">
let mymodel = #Html.Raw(JsonConvert.SerializeObject(Model));
</script>
--Import your script file after creating javascript variable and mymodel should then be available
<script type="text/javascript" src=""></script>
--Use mymodel in your script file
There are four ways to do this, you found two of them. I'll give you the pro's and cons in order of complexity:
AJAX:
It's not that hard, use the "fetch" method built into the window object. But, it's asynchronous so you have to deal with callbacks in JavaScript, you will need to secure the API so it only accepts authorized clients (usually done with OAuth, but you could just inject an authorization code for the client JavaScript to use), and you need to identify yourself (like a session) to the API to get the right data so that is another code. Oh wait, we have to inject a code? So what's the point of using AJAX? True, only use AJAX when you need to dynamically get new data without reloading the page!
JavaScript injection:
You never want to inject into a .js file, they should be static and that's why you discovered it won't work. So you have to inject some JavaScript code creating variables into the page that is loading the JavaScript. That's what you proposed and that is completely fair to do. It's isn't a hack. It should be one variable with a JSON string.
Cookie:
Put the data into a temporary cookie delivered with the page and read the cookie from JavaScript. This is cleaner than the variable solution, but isn't the simplest way.
HTML injection:
There is one other possibility for using #Model, instead of injecting the JSON string into a JavaScript variable, which requires injecting JavaScript tags too, put it into a property on an HTML element and then access the property from JavaScript. This is simpler and my preferred method. Property names beginning with "data-" are designed for this.

<%= %> syntax in Typescript/Angular

I'm working on an Angular project that makes use of a variable called WEB_HOST. I can see in another file where the variable is defined (it's somehow defined in a class called ProjectConfig).
Definition (simplified):
export class ProjectConfig {
WEB_HOST = 'https://example.com'; // I didn't think properties could be assigned here?
constructor() { ... }
}
Now, from a completely separate *.ts file, this obviously doesn't work:
let x = WEB_HOST; // x is undefined
However, in the same file, some existing code manages to access the variable's value by using a bizarre string interpolation:
let x = `<%= WEB_HOST %>`; // x == 'https://example.com'
What is going on here? I've never seen this <%= syntax before. Is it part of Angular? Typescript? I haven't been able to find any documentation on what it does.
I also don't know how it manages to get a property out of ProjectConfig (and I'm not sure it's a class property either... the definition being outside of any class function confuses me too).
So, this is ASP Tags.
If you take a look at the following from w3schools. https://www.w3schools.com/asp/showasp.asp?filename=demo_syntax_tags
You will see that it is used in the HTML for templating. It can also be used I believe in other files as it is processed on the server before the client application runs on your browser.
HTH
Looks like ERB, a Ruby templating engine that Ruby on Rails uses.
https://codingbee.net/tutorials/ruby/ruby-the-erb-templating-system
Others have mentioned that various languages use <%= some_code_here %> for templating.
Regardless of what language is processing it, I imagine your .ts file runs through some server side framework, that will put some string value in place of WEB_HOST, and then the .ts file will be transpiled to JS.
You could try this way on HTML file
{{window.location.origin}}
if it doesn't recognize the window variable we might need this in ts file
declare const window;

Best way to store .resx string in an object?

In my application I added the multilanguage support following this documentation.
Now I'm facing an issue: I need to translate also some javascript plugins, so I need to use the .resx string inside the js logic:
For access to those strings I can use the IStringLocalizer in the specific controller, let's suppose that the string above are part of UserController, I can access declaring in the View this:
#inject IStringLocalizer<UserController> Localizer
and then:
<h2>#Localizer["LastName"]</h2>
Suppose now that I need to pass LastName string in something like a JQuery plugin
localization. For doing so, I actually found a workaround, which consists to declare a javascript variable in the required View:
#inject IStringLocalizer<UserController> Localizer
#section UserScript{
<script>
var Lang = {
PasswordEqual: '#Localizer["PasswordEqual"]',
PasswordMismatch: '#Localizer["PasswordMismatch"]',
}
</script>
}
so I can access inside the javascript code to the Lang object and localize the plugin eg:
$('#birthDate').daterangepicker({
singleDatePicker: true,
locale: {
format: 'DD/MM/YYYY',
daysOfWeek: [
Lang.Sunday,
Lang.Monday,
This works, but it's really huge to mantain for the following reason:
I need to declare in each .cshtml file which require a script localization the Lang object
I need to set each time the object key for the specific string available in the IStringLocalizer
If I change a string key, I also need to update all the files manually.
What I'm looking for:
I'm looking for a solution that automatically fills the Lang object with all the properties available in the .resx file loaded in the current View.
I guess the best place for handle this is _Layout.
Someone could help me?

What is the standard workaround for dynamic js files

Is there a standard workaround for something like this in ASP.NET:
//myinclude.js
$(document).ready(function() {
for(recs=0; recs < {{server-side-value}}; recs++) {
// process records
}
});
Note this is a js file. I know about WinForms ability to insert dynamic quoted scripts into the page. But how about a page's js file that is dependent on server-side values? I know you can use something like:
//myview.cshtml
var instance = new MyObject(<%= ServerSideValue =%>);
and include it on the page to pass it to the js file, but I'm wondering about the architecture of keeping js separate from html code so that an html/css designer can work with the template free of javascript; keeping everything separate. I primarily use MVC now.
What are some of the patterns to deal with this? Is the only solution dynamically inserting js into the actual page or having partial views included separately into the page.? Or is there a way to sprinkle server-side values in separated js? In short, no dynamic js files?
I'm not trying to fix an exact project at this time, I have just been curious about this on past projects.
Thanks...
There are multiple ways to achieve this. One of the ways would be populating your data into a Javascript objects on the HTML page directly.
//myview.cshtml
<script>
var pageData = {
name : '#variable1',
value1: #value1
};
</script>
And, in the javascript file:
//pageUI.js
if (pageData) {
$('#page_tile').html(pageData.name);
}
I am sure you can optimize a whole lot (for example, having a single communication between the server side data and the client side code). At the end of the day, you want to make sure that your javascript code can be resusable.
for example one can do this:
A. have the main .js code read any context-specific parameters from the current window like this (page.js):
!function(window){
var configData = window.MyAppNameConfigData;
// rest app code here..
}(window);
B. the server side script can inject these context-specific data in the page's html like this:
<script>
window.MyAppNameConfigData = {
param1: //..
param2: //..
// etc..
};
</script>
Note if needed make sure that the page.js is enqueued/loaded after the data have been injected/inserted (using a script dependency chain for example)
If it's not "inline" (on the View/Page itself), you could do a Partial View/Page:
Trivial example: _PartialJs.cshtml
$(document).ready(function() {
var foo = "#DateTime.Now.Year";
});
Then in your view:
<script>
#Html.Partial("_PartialJs")
</script>
Renders:
<script>
$(document).ready(function() {
var foo = "2015";
});
</script>
Hth...

Call an external .js file javascript function without a long parameter list

I have two MVC Razor views (.cshtml) that have a virtually identical Javascript function within them.
In order to de-duplicate my javascript code I want to extract the Javascript from the views to a single external Javascript file (.js) containing the function (with a parameter that can be used to differentiate the minor differences need for each view).
The Javascript in the views contains Razor syntax to access many asp.net resource file (.resx) text values (e.g. var foo = '#ResourceFileName.Bar';) which the Razor engine unfortunately does not parse for me.
To overcome this I could pass all the resource file text values to the function in the .js file as parameters – but I prefer not to do that as the parameter list would become very large.
The RazorJS package (http://www.nuget.org/packages/RazorJS) will allow me to use Razor syntax within a .js file but this package was last published way back in 2011, which worries me.
What techniques could I use to call the externalised function without a huge long parameter list ?
What techniques could I use to call the externalised function without
a huge long parameter list ?
It doesn't need to be a huge parameter list. A single parameter containing all the necessary resource properties will be enough:
<script>
var args = #Html.Raw(Json.Encode(new
{
foo = ResourceFileName.Foo,
bar = ResourceFileName.Bar,
baz = ResourceFileName.Baz
}));
myFunction(args);
</script>
and then in your function you can access all those properties:
function myFunction(args) {
// you can use args.foo, args.bar and args.baz here
}

Categories

Resources