简体   繁体   中英

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.

NOTE:I know that the code above doesn't work but I'd like to know if embedding JavaScript in Razor is possible.

You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side.

As a workaround, you can use placeholder to generate the url. Then use .replace() method to generate the actual url.

HTML

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

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:

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. Then you wouldn't need any JavaScript. Or, you could use JQuery to attach a function to the click event of your link:

<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.

It very much depends on what you are trying to do. It seems like maybe you just need a form, to me.

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