embedding javascript variable within razor syntax

2020-03-12 05:42发布

I have a method that looks like this

function endcall_click(leadid) {
    document.location = '@Url.Action("index","dispo",new{id=leadid})/';
}

Of course it doesn't work because it treats "leadid" as a server side variable but I want to inject the javascript variable passed into the method.

I tried wrapping lead id in but that didn't work.

function endcall_click(leadid) {
    document.location = '@Url.Action("index","dispo",new{id="<text>leadid</text>"})/';
}

Any ideas?

2条回答
神经病院院长
2楼-- · 2020-03-12 06:02

I finally found the solution (*.vbhtml):

<script type="text/javascript">
function razorsyntax() {
    /* Double */
    @(MvcHtmlString.Create("var szam =" & mydoublevariable & ";"))
    alert(szam);

    /* String */
    var str = '@stringvariable';
    alert(str);
}
</script>
查看更多
Juvenile、少年°
3楼-- · 2020-03-12 06:07

You can't inject javascript variable to a script that is evaluated at the server simply because at the moment this script executes and generates the output this variable hasn't yet come to existence. The only way to achieve this is to manipulate the resulting string:

function endcall_click(leadid) {
    document.location = '@Url.Action("index", "dispo")/' + leadid;
}

The drawback is that this assumes manipulating the routes in javascript and if you decide to change them on the server the code might break.

查看更多
登录 后发表回答