0

Very strange behavior that I could not understand where the razor variable completely disappears as seen in the screenshot (@SomeID disappears). My goal is to get the id from the server, then assign it to a javascript variable. The problem appears to happen when the razor variable is null and also no matter where I assign this variable even with document ready.

The View:

@{
long? SomeID= (long?)ViewBag.BoxID;
}

<script type="text/javascript">
var testVariable;

function OnElementLoaded() {
    testVariable = @SomeID; 
}     
</script>

enter image description here

3
  • 1
    don't dump data directly into a JS context. as you see, it's very easy to generate JS syntax errors, which then kill the entire JS code block. always output via json, which will handle the translation from native->js for you, including any necessary quoting/escaping. Commented Aug 11, 2016 at 21:10
  • @MarcB, could you please clarify about the benefit of json in this situation. I already send the data wrapped in a model that has a c# type. Commented Aug 11, 2016 at 21:21
  • 1
    in your case, it's a long value, so not a big deal. but consider a string. foo = "Miles O'brien";, and then dump that into js: testVar = Miles O'Brien;. now you've got an undefined variable (Miles) and a flat-out syntax error with an unexpected extra undefined variable (O) followed by an unterminated string 'Brien Commented Aug 11, 2016 at 21:23

1 Answer 1

1

Asssuming SomeID variable has some value like 2545 in it. Razor will render your code like below.

testVariable = 2545; 

But your variable is nullable type. That means it could have a null value. I believe your ViewBag.BoxID value is null, hence your variable became null and your resulting HTML became,

function OnElementLoaded() {
    testVariable = ;
}

One thing you can do is to wrap the value in quotes. But this works best for non numeric values(strings).

function OnElementLoaded() {
    testVariable = `@SomeID`; 
} 

For numeric values, It is best do a null check and assign value. If the value of your c# expression is null, set to 0 ( or any default value you want);

For example, the below code will set 0 if the ViewBag.BoxID expression returns null.

@{
    long? SomeID = ViewBag.BoxID!=null ? (long?)ViewBag.BoxID:0;
}

<script type="text/javascript">
    var testVariable;

    function OnElementLoaded() {
        testVariable = @SomeID;

    }
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Wrapping in quotes surely fix the problem! Based on your second sentence, how do I even define/initialize it if I wanted to?
You can add a null check and set a default value if needed. See the updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.