kabouterhuisje
kabouterhuisje

Reputation: 67

How do I set Razor variabele in Javascript?

I'm setting Razor variables with data from my controller like this:

@{
    var filterData = ((ShipmentController)this.ViewContext.Controller).GetNoCmrs(new List<int>() { 1 });
}

I want to change this data based on the selected option the user selects (within a select).

<script>
    var x;
    function loadShipmentsByCondition() {
        x = document.getElementById("conditionSelect").value;
        if (x === "CMR not received") {
            @filterData = @newData;
        } else if(x === "Not invoiced") {
            console.log("INVOICE");
            @filterData = @otherData;
        }
    }
</script>

Is this possible? Or if not, how can I do this efficiently? I'm using MVC ASP.NET and vue js as front-end.

Thanks

Upvotes: 0

Views: 59

Answers (1)

Mayron
Mayron

Reputation: 2394

Unfortunately, you cannot get JavaScript to change a value of your backend C# code because JavaScript, once rendered on the frontend, does not know anything about your C# code on the server.

However, you can assign a C# value to a JavaScript variable before it leaves the server. What this is doing is just injecting the value of @filterData into the html page in the script and then is assigned to the real JavaScript variable in the actual JS environment during runtime:

<script>
    var x;
    var filterData = @filterData;
    var otherData = @otherData;
    var newData = @newData;

    function loadShipmentsByCondition() {
        x = document.getElementById("conditionSelect").value;
        if (x === "CMR not received") {
            filterData = newData;
        } else if(x === "Not invoiced") {
            console.log("INVOICE");
            filterData = otherData;
        }
    }
</script>

So you are essentially converting those C# variables into JavaScript variables, but if you really need to change the C# variables then you would have to do a postback, or AJAX call to the server.

Upvotes: 3

Related Questions