Share via


Assign a value to ASP variable inside Javascript function - is it possible?

Question

Wednesday, May 7, 2014 1:24 PM

I'm trying to assing a value to an ASP variable inside Javascript function.

It goes like this:

@{
    var daySelection = "";
}

@for(int i = 1; i <= numDays; i++){
    <div class="singleDay" onClick="daySel(@i)">
        Day @i
    </div>
}

<script>
    function daySel(day){
        alert("Day: " + day + " was selected.");

        @daySelection = day;
    }
</script>

The alert works well.

But assigning day value to daySelection failed. Any suggestions?

 

Many thanks!

All replies (3)

Wednesday, May 7, 2014 1:49 PM ✅Answered

Unfortunately, this isn't possible.  The C# is compiled and run on the server, while the Javascript runs on the client side.

EDIT: For example, the following .cshtml file:

@for(int i = 0; i < 10; i++)
{
    @:The value of i is: @i<br />
}

Generates this HTML:

The value of i is: 0<br />
The value of i is: 1<br />
The value of i is: 2<br />
The value of i is: 3<br />
The value of i is: 4<br />
The value of i is: 5<br />
The value of i is: 6<br />
The value of i is: 7<br />
The value of i is: 8<br />
The value of i is: 9<br />

Only the HTML is sent to the client.  The user's computer knows nothing about your Razor code.


Sunday, May 11, 2014 3:29 AM ✅Answered

But assigning day value to daySelection failed. Any suggestions?

What emu said is correct. 

But here's a workaround, courtsey of some ajax calls. 

Run this example below: 

First I created a file called SelectDay.cshtml (which is based on your code you wrote above). But I added a jquery ajax call. See javascript comments

@{
    var daySelection = "";
}
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>

@for (int i = 1; i <= 7; i++) {
<div class="singleDay" onclick="daySel(@i)">
        Day @i
    </div>
}

<div id="selectedDay"></div>

<script>
    function daySel(day){
        // at this point, you're going to call /displayDay.cshtml and pass the day value
        $("#selectedDay").load("displayDay.cshtml?day=" + day);
        // displayDay.cshtml will run on the server, set a session variable, and display a message back
        // message output will be displayed inside div id "selectedDay" 
    }
</script>

Create another program, let's call it "displayDay.cshtml" 

@{
    // let's get the querystring
    string day = Request.QueryString["day"];
    // do whatever you want, say assign it to a session variable
    Session["day"] = day; 
    // even send back a message to your "SelectDay.cshtml" program.
    Response.Write("Server says you selected day " + Session["day"]);
}

Run SelectDay.cshtml in your browser, click on any of the days. You'll see the message returned by the server.


Tuesday, May 13, 2014 11:01 AM

Well! That is EXACTLY what I did!

Works like a charm!