How to set javascript variables using MVC4 with Ra

2019-01-07 09:12发布

Can someone format the code below so that I can set srcript variables with c# code using razor?

The below does not work, i've got it that way to make is easy for someone to help.

@{int proID = 123; int nonProID = 456;}

<script type="text/javascript">
    @{

     <text>  

    var nonID =@nonProID;
    var proID= @proID;
    window.nonID = @nonProID;
    window.proID=@proID;

    </text>
}
</script>

I am getting a design time error

enter image description here

12条回答
Melony?
2楼-- · 2019-01-07 09:46

One of the easy way is:

<input type="hidden" id="SaleDateValue" value="@ViewBag.SaleDate" />
<input type="hidden" id="VoidItem" value="@Model.SecurityControl["VoidItem"].ToString()" />

And then get the value in javascript:

var SaleDate = document.getElementById('SaleDateValue').value;
var Item = document.getElementById('VoidItem').value;
查看更多
做自己的国王
3楼-- · 2019-01-07 09:50

I found a very clean solution that allows separate logic and GUI:

in your razor .cshtml page try this:

<body id="myId" data-my-variable="myValue">

...your page code here

</body>

in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):

$("#myId").data("my-variable")
查看更多
虎瘦雄心在
4楼-- · 2019-01-07 09:51
@{
int proID = 123; 
int nonProID = 456;
}

<script>

var nonID = '@nonProID';
var proID = '@proID';
window.nonID = '@nonProID';
window.proID = '@proID';

</script>
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-07 09:52

I've seen several approaches to working around the bug, and I ran some timing tests to see what works for speed (http://jsfiddle.net/5dwwy/)

Approaches:

  1. Direct assignment

    In this approach, the razor syntax is directly assigned to the variable. This is what throws the error. As a baseline, the JavaScript speed test simply does a straight assignment of a number to a variable.

  2. Pass through `Number` constructor

    In this approach, we wrap the razor syntax in a call to the `Number` constructor, as in `Number(@ViewBag.Value)`.

  3. ParseInt

    In this approach, the razor syntax is put inside quotes and passed to the `parseInt` function.

  4. Value-returning function

    In this approach, a function is created that simply takes the razor syntax as a parameter and returns it.

  5. Type-checking function

    In this approach, the function performs some basic type checking (looking for null, basically) and returns the value if it isn't null.

Procedure:

Using each approach mentioned above, a for-loop repeats each function call 10M times, getting the total time for the entire loop. Then, that for-loop is repeated 30 times to obtain an average time per 10M actions. These times were then compared to each other to determine which actions were faster than others.

Note that since it is JavaScript running, the actual numbers other people receive will differ, but the importance is not in the actual number, but how the numbers compare to the other numbers.

Results:

Using the Direct assignment approach, the average time to process 10M assignments was 98.033ms. Using the Number constructor yielded 1554.93ms per 10M. Similarly, the parseInt method took 1404.27ms. The two function calls took 97.5ms for the simple function and 101.4ms for the more complex function.

Conclusions:

The cleanest code to understand is the Direct assignment. However, because of the bug in Visual Studio, this reports an error and could cause issues with Intellisense and give a vague sense of being wrong.

The fastest code was the simple function call, but only by a slim margin. Since I didn't do further analysis, I do not know if this difference has a statistical significance. The type-checking function was also very fast, only slightly slower than a direct assignment, and includes the possibility that the variable may be null. It's not really practical, though, because even the basic function will return undefined if the parameter is undefined (null in razor syntax).

Parsing the razor value as an int and running it through the constructor were extremely slow, on the order of 15x slower than a direct assignment. Most likely the Number constructor is actually internally calling parseInt, which would explain why it takes longer than a simple parseInt. However, they do have the advantage of being more meaningful, without requiring an externally-defined (ie somewhere else in the file or application) function to execute, with the Number constructor actually minimizing the visible casting of an integer to a string.

Bottom line, these numbers were generated running through 10M iterations. On a single item, the speed is incalculably small. For most, simply running it through the Number constructor might be the most readable code, despite being the slowest.

查看更多
乱世女痞
6楼-- · 2019-01-07 09:52

This should cover all major types:

public class ViewBagUtils
{
    public static string ToJavascriptValue(dynamic val)
    {
        if (val == null) return "null";
        if (val is string) return val;
        if (val is bool) return val.ToString().ToLower();
        if (val is DateTime) return val.ToString();
        if (double.TryParse(val.ToString(), out double dval)) return dval.ToString();

        throw new ArgumentException("Could not convert value.");
    }
}

And in your .cshtml file inside the <script> tag:

@using Namespace_Of_ViewBagUtils
const someValue = @ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue);

Note that for string values, you'll have to use the @ViewBagUtils expression inside single (or double) quotes, like so:

const someValue = "@ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue)";
查看更多
Lonely孤独者°
7楼-- · 2019-01-07 09:54

This is how I solved the problem:

@{int proID = 123; int nonProID = 456;}

<script type="text/javascript">
var nonID = Number(@nonProID);
var proID = Number(@proID);
</script>

It is self-documenting and it doesn't involve conversion to and from text.


Note: be careful to use the Number() function not create new Number() objects - as the exactly equals operator may behave in a non-obvious way:

var y = new Number(123); // Note incorrect usage of "new"
var x = new Number(123);
alert(y === 123); // displays false
alert(x == y); // displays false
查看更多
登录 后发表回答