Utilizing JavaScript within Razor templates

Is there a way to achieve something like this:

<input type="text" id="ZIP" name="ZIP" />
<a <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed859f888bd0adb89f81c3ac8e99848283">[email protected]</a>("VerifyZIP","Controller",new{ZIP = document.getElementById('ZIP').value})>Send To Controller</a>

Essentially, I want to send the value from ZIP input field using an <a> tag to my controller.

NOTE: Although the code above is not functional, I am curious about the possibility of embedding JavaScript in Razor.

Answer №1

Passing a JavaScript variable to Url.Action on the server-side is not possible.

To work around this limitation, you can use a placeholder in the URL and then replace it with the actual value using the .replace() method.

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>

Answer №2

Yes, it is definitely possible to include JavaScript in Razor and utilize values from your Model object to create dynamic scripts. An example would be:

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

There are various approaches to achieve the desired outcome. One option is to design a form using Html.BeginForm and customize the submit button to resemble a link. This eliminates the need for JavaScript. Another alternative is to employ JQuery to assign a function to the click event of your link:

<input type="text" id="ZIP" name="ZIP" />
<a <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92fae0f7f4afd2c7e0febcd3f1e6fbfdfc">[email protected]</a>("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>

You could also implement the above as an inline function with an onClick attribute, if preferred.

The approach you take greatly depends on the specific requirements of your project. It appears that a simple form might suffice for your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experimenting with a customizable Vue.js autocomplete feature

Check out this sample code: https://jsfiddle.net/JLLMNCHR/09qtwbL6/96/ The following is the HTML code: <div id="app"> <button type="button" v-on:click="displayVal()">Button1</button> <autocomplete v- ...

Three.js Photometric Function

Is there a way to specify a photometric function in Three.js? Currently, I am utilizing a Lambert material: new THREE.MeshLambertMaterial({ color: 0xffffff }) However, I am interested in using a Lommel Seeliger but I am unsure of the process and locatio ...

Retrieving data in batches using HTTP in JavaScript

My RESTful service has the capability to batch requests, which I am attempting to do using the Fetch API: let req1 = { url: "/cups/count", options: { method: 'GET', headers: { 'Content-Ty ...

Full-Screen Popup Overlayaptic

Is it possible to create a popup that covers the entire browser window, including the search bar and other windows besides just the webpage area, for a very large interactive element? ...

Extract user's location using JavaScript and transfer it to PHP

My goal is to utilize JavaScript to retrieve the latitude and longitude, then compare it with the previous location, similar to how Facebook authenticates logins from different devices. To accomplish this, I have implemented 2 hidden fields which will capt ...

Display a hoverable button for a singular element within an array during the process of mapping through the array

const ChatWidget = () => { const bodyRef = useRef(null) const [{messages,roomMessages,roomID,socket,user}, dispatch] = useStateValue() const [dropdown, setDropdown] = useState(false) useEffect(()=>{ const setScreen = () =>{ bodyRef.cur ...

`The functionalities of classList.add and classList.remove aren't behaving as anticipated.`

I'm currently working on a list of items (ul, li) that have a class applied to them which adds a left border and bold highlight when clicked. My goal is to reset the style of the previously clicked item back to its original state when a new item is c ...

Generating unique identifiers and names for duplicated input fields in a form, which change dynamically

Innovative approach: When dealing with multiple replicated inputs, changing the id and name attributes can be a hassle. How can we ensure that each input remains unique, especially in a real project with several inputs like component_date and component_own ...

The Three.js tweened property fails to reach its target value and ends up completing the animation while remaining stuck at its original value

I've been experimenting with implementing Tween in my WebGL project at to smoothly move the camera to a new position. Unfortunately, I'm facing challenges getting Tween to function as desired. When attempting to tween the camera.position.x valu ...

Using Selenium in Python to Navigate through a Modal Window

I'm currently involved in a project that involves scraping data from LinkedIn. Specifically, I am attempting to extract a list of companies that interest a particular individual (without the use of the API). The challenge I'm facing is that the w ...

Received a JSON value that cannot be converted into a tuple of two numbers in Typescript

I'm a beginner when it comes to TypeScript and I am struggling to find the solution to my question. In my project, there is a config.json file structured like this: { "api": { "baseUrl": "http://localhost:9000/api", "list": { "itemsP ...

Embedding HTML Tags within an array element

The task at hand involves adding an HTML element from Array Value to the Document Object Model template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: &a ...

Discovering the attribute of a DOM element (or, to be more precise, the class of a div)

Here's the code snippet I'm working on: <body class="asdf"> <span>hey! <div class='hideContent'>test</div> the ultimate experience</span> <span id="blarg">original</span> </b ...

Tips on expanding the express request interface

Currently, I am working with express and typescript. To enhance my express request interface, I have implemented the following code snippet:- Middleware.ts import { NextFunction, Request, Response } from 'express'; // eslint-disable-next-line @ ...

NextJS: Invalid element type provided: expected a string for built-in components or a class/function for composite components, but received an undefined value

Utilizing Nextjs, I've configured an index.js file in the /pages directory and a meta.js file in the /components/meta/ directory. However, during the rebuild process of my application, I encountered the following error message: Element type is inv ...

Executing a script that has been inserted into the page post-loading

I'm facing an issue where the script tag at the bottom of my project is not being executed after adding new pages later on. Main const fetch = (url, call) => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if ...

Compiling TypeScript files with an incorrect path when importing, appending "index" at the end of the @angular/material library

I'm currently working on creating a library to collect and distribute a series of Angular components across various projects, with a dependency on angular/material2. My objective is to eventually publish it on npm. However, I've encountered an i ...

Troubleshooting a dynamic JavaScript loading problem with jQuery on Cloud9

My current challenge involves dynamically loading JavaScript on a project at Cloud9 IDE. Specifically, the server file monitors changes in the project's file system and sends updates to the client using socket.io. The data file contains just one line ...

Issue encountered while activating react/jsx-sort-props [eslint-plugin-react Rules]

For my project, I am attempting to arrange props names alphabetically by utilizing the eslint-plugin-react plugin. After reviewing the example of the jsx-sort-props rules option at https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/js ...

The header cannot be adjusted once it has been sent to the client

Encountering an issue where I receive the error message "Can't set the header after they are sent to client" when the incoming request lacks basic authentication and jwt token. This error occurs because I am unable to prevent node.js from executing t ...