简体   繁体   English

在razor中嵌入javascript

[英]Embedding javascript in razor

Is there a way to do something like: 有没有办法做类似的事情:

<input type="text" id="ZIP" name="ZIP" />
<a href=@Url.Action("VerifyZIP","Controller",new{ZIP = document.getElementById('ZIP').value})>Send To Controller</a>

basically what I want to do is to send the value in ZIP input using <a> tag to my controller. 基本上我想做的是使用<a>标记将ZIP输入中的值发送到我的控制器。

NOTE:I know that the code above doesn't work but I'd like to know if embedding JavaScript in Razor is possible. 注意:我知道上面的代码无法正常工作,但是我想知道是否可以在Razor中嵌入JavaScript。

You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side. 您不能将JavaScript(Client Side)变量传递给Url.Action因为它是在服务器端处理的。

As a workaround, you can use placeholder to generate the url. 解决方法是,可以使用占位符来生成URL。 Then use .replace() method to generate the actual url. 然后使用.replace()方法生成实际的URL。

HTML HTML

<a href="#" onclick="redirect(this, event)" data-url='@Url.Action("GetAnn", "Home", new { CEP = "__PLACEHOLDER__"})'>Send To Controller</a>

JavaScript JavaScript的

<script>
    function redirect(elem, event) {
        event.preventDefault();
        window.location.href = elem.dataset.url.replace("__PLACEHOLDER__", document.getElementById('ZIP').value);
    }
</script>

It is very much possible to embed JavaScript in Razor, yes, and you can use values in your Model object to generate the JavaScript too, for example: 很有可能将JavaScript嵌入Razor中,是的,您也可以使用Model对象中的值来生成JavaScript,例如:

var foo = {someValue: '@Model.SomeValue,', someOtherValue: '@Model.SomeOtherValue'};

There are a few ways to achieve what you want to do, though. 不过,有几种方法可以实现您想要的。 You could create a form using Html.BeginForm and style the submit button like a link. 您可以使用Html.BeginForm创建一个表单,并将提交按钮的样式设置为链接。 Then you wouldn't need any JavaScript. 然后,您将不需要任何JavaScript。 Or, you could use JQuery to attach a function to the click event of your link: 或者,您可以使用JQuery将函数附加到链接的click事件:

<input type="text" id="ZIP" name="ZIP" />
<a href=@Url.Action("VerifyZIP","Controller",new{ @id = "my-link")>Send To Controller</a>

<script>
    $('#my-link').click(function () {
        var url = '@Url.Action("VerifyZIP","Controller")';
        var zipValue = $('#ZIP).val(); 
        var params = { zipValue };
        $.get(url, params, function(response) {
            // do something with response
        );
    });
</script>

Of course you could do the above as a inline function an onClick attribute, if you wanted. 当然,如果需要,您可以将上述操作作为onClick属性的内联函数执行。

It very much depends on what you are trying to do. 这在很大程度上取决于您要做什么。 It seems like maybe you just need a form, to me. 对我来说,似乎您只需要一张表格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM