MVC Url.Content with javascript local variable - c#

I have problem with this:
var id=5;
var el = $("MainPhotoHolder");
el.attr("src", '#Url.Content("~/Page/GetImage/" + id)');
id is a local javascript variable, but it gives me an error saying that is not in the context. My question is how do i point out that it should be a javascript variable and not a c# one ...?

You cannot mix JavaScript and Razor in this way. Razor does not have any reference to it so it cannot use it to generate your link. Try this:
el.attr("src", '#Url.Content("~/Page/GetImage/")' + id);
You might have to use "Url.Action" if you're serving the images from a controller rather than a static repository.

Related

Do variable check only once in blazor

I have several razor pages I want to do checks on using the current URL value.
They currently all have in their #code{} block URLs like:
Razor Page 1: MyNavigationManager.NavigateTo("sample_domain/sub_page_1?i=" + variable, forceLoad: true);
Razor Page 2: MyNavigationManager.NavigateTo("sample_domain/sub_page_2?i=" + variable, forceLoad: true);
Razor Page 3: MyNavigationManager.NavigateTo("sample_domain/sub_page_3?i=" + variable, forceLoad: true);
I would like to remove the sample_domain/ part if the URL has localhost in it.
So I have seen here that I can get the current urls by Injecting before using it on .razor pages #inject NavigationManager MyNavigationManager and using MyNavigationManager.Uri to get the url.
Now I implemented it doing the following in each of the razor pages code block:
//check if the url has localhost
string domain_url = MyNavigationManager.Uri.ToString().Contains("localhost") ? "" : "/sample_domain";
MyNavigationManager.NavigateTo($"{domain_url}/sub_page_1?i=" + variable, forceLoad: true);
But now I only want to do the check once, and set the variable there, e.g. the domain_url. Then use that variable in the different razor pages without explicitly checking and setting it in each page. Maybe something like a global variable? session? But not sure how to go about that? Thanks.
You can call a method in a service to do that for you. For example, create a service MyService.cs, and have a method like GetUrl
public string GetUrl(string nav_url)
{
return nav_url.ToString().Contains("localhost") ? "" : "/sample_domain";
}
Inject the service #inject MyService MService in _Imports.razor, also add the service in the Program.cs file builder.Services.AddSingleton<MyService>(); then call the method like:
MyNavigationManager.NavigateTo($"{MService.GetUrl(MyNavigationManager.Uri)}/sub_page_1?i=" + variable, forceLoad: true);

Using global C# variables in Typescript

When writing Javascript code within a Razor/cshtml file, one may write code as follows:
if (lSelectedID == "#(Globals.MyGlobalVariable)") {
...
}
where Globals.MyGlobalVariable is a C# variable.
If Globals.MyGlobalVariable==123, then the resulting Javascript on the client will be
if (lSelectedID == "123") {
...
}
The above is very handy. But how to do the same in Typescript? I.e. how to insert a C# global variable (or result of C# function call or whatever) into typescript before the typescript file is transformed to Javascript?
It's not best practice to include JavaScript and CSS directly into your CSTHML. Rather you should have them in their own file and reference them in your view.
If your JavaScript is going to need some value from C# then you should store it by using data attribute in your HTML elements.
Example:
<span id="myGlobalVariable" data-value="123456">MyGlobalVariable</span>
Then in your TypeScript get data you have set in your View
let myGlobalVariable = document.getElementById("myGlobalVariable").dataset.value;
if (lSelectedID == myGlobalVariable) {
}
I think the easiest thing to do here would be to replicate your global variables in Typescript on the client side. This is how I've done it for my last two projects.
So on the server side you would have:
// C#
public class Globals()
{
public int GlobalNum {get;} = 0;
public string GlobalString {get;} = "123";
}
And on the client side, in Typescript it would be:
// Typescript
export enum Globals{
GlobalNum = 0;
GlobalString = "123";
}
Now you can forget about the difficulty of trying to connect Razor (which renders server-side) to your Typescript (which executes on the client side), while still having a clear and obvious set of globals to refer to.
You code can then become:
// Typescript
if (lSelectedID == Globals.GlobalString) {
//...
}
The only thing you need to keep in mind is that your global variables exist in two places - once on the server side and once on the client side.
Typescript demands that you replicate a lot of your server-side classes on the client side anyway, for receiving fetch response data properly, for example, so the addition of a Globals class/enum should not be too much of a break from the norm.

Assign Viewbag to js variable throws an exception

I want to assign viewbag to my javascript variable to compare some value from model
<script>
var uid = "..."; // this retrieves some variable from external server
#ViewBag.someId = uid;
</script>
...
#If(Model.AppDataFbId == ViewBag.someId){ ... }
But this throws an exception:
Uncaught SyntaxError: Unexpected token =
What can I do?
As the comment said , ViewBag is server side code, you can't set ViewBag with js variables in C# code block but you can set js variables with ViewBag value. Like:
<script>
var uid ='#ViewBag.someId';
</script>
If you just want compare Model.AppDataFbId with js variable(uid), add the logic in js code.
<script>
function compare(){
if('#Model.AppDataFbId'==uid){
//other code
}
}
</script>
The variable #ViewBag.someId is used by the server to generate the static HTML page it sends to the browser. It doesn't make sense for the browser to be able to directly change that variable on the server after it receives the HTML.
It looks like you want the value of uid to decide the page contents. If you want these changes to be made server-side (i.e. before the page is sent to browser) then you will have to get your MVC controller to grab this value from the external server before it returns its view. A more conventional way to solve the same problem is to transform the page in the browser with Javascript.

Razor cshtml getting parameters from another cshtml

I am new to C# and Razor v3.
I have a php web app that I am trying to convert to ASP.NET. I decided, mainly due to ease, to use Razor. What I am making is a Single Page App.
The way I have it laid out in PHP is via 3 php files, 1 of which essentially passes the variable values to the main index.php like so, for example
vars.php
if (isset($_GET["lang"])) {
$lang = mb_strtolower($_GET["lang"]);
} else {
$lang = "el";
}
and this is how my index.php uses that variable
<html lang=<?php echo "\"".$lang."\"";if($page2go===1) {echo " itemscope itemtype=\"http://schema.org/Article\"";}?>>
Now, everytime index.php is called, I call on vars.php by using
<?php require_once('./scripts/vars.php');?>
This is how my values are passed into my index.php.
I have found I can do the similar by including my if statements and variable delcarations at the top of my index.cshtml. Like so
#{
var lang = "";
if (!String.IsNullOrEmpty(Request.QueryString["lang"]))
{
var interior = Request.QueryString["lang"];
interior.ToLower();
lang = interior;
}
else
{
lang = "el";
}
}
Now I perform a LOT of if operations like that, making my index.cshtml an absolute mess.
Is there a way to pass the variable values, like I do in php by including vars.php?
Thanks a lot for your time.
You should recreate your one-page application to an MVC application.
All the request processing (and other complex logic) will take place in the controller action.
The controller action will in turn pass all variables that you need to the view that you have created.

Access global static variable from code behind through Javascript

I'm having some issues accessing a static variable in a class when getting it from a code behind function called from javascript.
My aspx page:
<script type="text/javascript">
function AlertMsg(msg) {
var msg213 = "<%= GetValue(" msg ") %>";
alert(msg + '::' + msg213);
}
</script>
Code behind:
public string GetValue(string sString)
{
return MyNamespace.MyClass.MyStaticVariable;
}
I set this variable in a page_load in another page. I'm accessing the javascript function by invoking it from a C# WebBrowser application. It's always empty.
Any ideas?
I think you just need to add '+' around your reference to 'msg'
var msg213 = "<%= GetValue(" + msg + ") %>";
ASP.NET isn't like a desktop application, any variables written on another page will be lost when moving to another page. You need to save the value to somewhere persistent.
Session
Cache
Database
App or Web Config files.
Variable needs to be a const or static
Try this
'<%= GetValue("Some Value") %>';
This means when page rendering, GetValue method calls and return string will be write in the document body, like Respose.Write
This will only happend when when page rendering and no further call will happend.
I think part of the confusion is coming from the formatting in the code. If you look at just the server tag: <%= GetValue(" msg ") %>, you will see that the GetValue method is being invoked, and the literal string msg is being passed in. There are quotes around the server tag itself, but those do not affect what is inside the server tag. You are not passing in the value of the msg parameter of the JavaScript function.
Server methods cannot be invoked from JavaScript in such a simple manner, it requires using something like AJAX to accomplish.

Categories

Resources