1

この行

$('.current').val(page + ' of ' + @lastPage);

最後の括弧に「構文エラー」を示す赤い波線で下線が引かれます。

ただし、この行

setPage(@lastPage);

完全に正常に動作します。

一体何が起こっているのですか?私の見解ではスクリプトが完全に機能しなくなり、かなりイライラしています。

どなたか、この件に光を当てていただけないでしょうか。

4

2 に答える 2

5

@lastPage は、サーバー側で評価されるため、javascript がそれを見ると純粋なテキストになります。jQuery を次のように変更したい場合があります。

$('.current').val(page + ' of @lastPage');

また

$('.current').val(page + ' of ' + '@lastPage');

@lastPage が 3 と評価された場合、レンダリングされた JS は次のようになります。

$('.current').val(page + ' of ' + 3);

あなたはそれがこのように見えることを望みます

$('.current').val(page + ' of 3');

また

$('.current').val(page + ' of ' + '3');
于 2013-06-06T23:05:30.340 に答える
0

You're thinking that the Javascript and the (C#) Razor syntax are working together at the same time in the same environment (like how HTML and Javascript do normally). They don't. It's not correct to think of it as "Razor assigning values to jQuery variables" as well.

The key thing to understand here is that the Razor syntax will be evaluated in the server, before it sends a response back to your browser (say, an HTML page). The Javascript will evaluate in the browser, after it's received a response from the server. So it's essentially two environments. A way of thinking about it is that Razor prepares the environment for Javascript to run in on the browser.

Say, for example, your Razor code is like this:

@{ 
    var id = "foo";
}
$('#@id').show();

Your Javascript isn't going to even notice that there was Razor in it, because by the time it gets to it, it would've looked like this:

$('#foo').show();

That's the reason why Javascript can't assign to Razor as well; just because of the fact that by the time Javascript "gets its turn" at evaluating, Razor would've been all done and gone. Your context is now at the client (browser), and your server is done whipping up whatever your request against it would've needed.

于 2013-06-06T23:16:21.893 に答える