简体   繁体   中英

Is it possible to pass a jquery variable to a c# function in an MVC view without using ajax?

I have an MVC view, like this:

@{ Func<int, int, int> function = (a, b) => a + b; } 

<script type="text/javascript">
    $(document).ready(function () {

        var answer = @(function(1,2));
        $("#answer").html(answer);

    });
</script>

<div id="answer"></div>

I would like to pass jquery variables to the function instead of the literals 1 and 2. Can this be done without using ajax?

You're trying to mix server-side execution of code with client side execution of code. The C# code here is server side, and will be executed at the time of page render. The JavaScript is client-side, and fires much later than the server side code did. In short, no, you cannot accomplish this.

In fact, it is for this very reason that AJAX was invented - executing server-side code at the client after document load. :)

I'm being somewhat literal when you say "without using ajax"...

You can have a hidden field and then have JavaScript populate the field and then cause a form submit. So it would be a regular POST/GET on the server (no ajax)

<script type="text/javascript">
    $(document).ready(function () {
        var answer = @(function(1,2));
        $("#answer").val(answer);
        $("#myAutoForm").submit();
    });
</script>

<form id="myAutoForm" action="....">
<input type="hidden" id="answer" value="">
</form>

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