lucas js
lucas js

Reputation: 23

Embedding javascript in razor

Is there a way to do something like:

<input type="text" id="ZIP" name="ZIP" />
<a [email protected]("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.

Upvotes: 0

Views: 141

Answers (2)

Satpal
Satpal

Reputation: 133453

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>

Upvotes: 1

chipples
chipples

Reputation: 195

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 [email protected]("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.

Upvotes: 0

Related Questions