简体   繁体   中英

How to make a javascript value equal to the value that I receive from my Razor code

I'm new to MVC and am not sure if this is even possible but I want to know how I can make a variable inside of my javscript function be to a equal the value that I am grabbing from my razor code.

Here is my code

function create() {

        var site

        @if (@so.invSiteID == null) {
            var siteRazor = 0;
        }
        else {
            var siteRazor = @so.invSiteID;            
        }
}

So is it possible for me to make my "siteRazor" equal to my "site" variable?

Also, I tried this

if (@so.invSiteID == null) {
            site = 0;
        }
        else {
            site = @so.invSiteID;            
        }

But it didn't matter if the statments were true or false it would always run through both. If I can get a brief explanation as to why that didn't work that would be awesome

Create a hidden field and assign the value of your variable there:

@Html.Hidden("siteId", @myvariable)

Then, in JS, you can reference the value of the hidden field:

var siteIdVal = document.getElementById("siteId").value;

In your Razor code, if you need to take an extra step to ensure that code is included as-is in the output and not treated as C#.

If you don't have an html tag, you can use the <text></text> or @: syntaxes to tell Razor not to run the line(s) as C# code but just treat them as part of the output. See here for details: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.1#explicit-delimited-transition

For example, the output of this is nothing. You've assigned ac# variable that is unused.

@if (@so.invSiteID == null) {  // note: the second @ here is not 
                               // necessary because you are in a c# block
    var siteRazor = 0;   // << var is a c# keyword and the `if` is a c# block
}

Instead, you could use:

@if (so.invSiteID == null) {
    @: var siteRazor = 0;
}
// ... rest of code

My suggestion would be to minimize the amount of C# code as much as possible in your Razor files, and always think about what the output you are creating. (View-source in the browser to see the actual output if needed.)

That said, you can simplify your code greatly if you use the null coalescing operator.

function create() {

    var site = @(so.invSiteId ?? 0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM