1

I'm using Alpine.js (included via CDN) in my ASP.NET Razor Page, but can't make it work.

Code Screenshot

VSCode shows an error: CS0103: The name 'change' does not exist in the current context'.

How can I use the @change, @keyup and @submit directives in my project?

1

1 Answer 1

3

The problem with your code is that in razor pages the @ sign is used to toggle between C# and HTML code. There are actually two solutions.

  1. You can simply escape the @ sign by typing @@

Taken from the alpine example page this would look like this

<button x-data @@click="$store.darkMode.toggle()">Toggle Dark Mode</button>

...

<div x-data :class="$store.darkMode.on && 'bg-black'">
    ...
</div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.store('darkMode', {
            on: false,

            toggle() {
                this.on = !this.on
            }
        })
    })
</script>

The other solution would be to use the x-on Event coming with Alpine JS. you can change the click line to this:

<button x-data x-on:click="$store.darkMode.toggle()">Toggle Dark Mode</button>

This will have the same effect without the need to escape any characters. x-on can also work with Change, KeyUp etc. Just pick whatever solution you like best!

Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to use <form @@submit.prevent="..."> as docs, however the double quotes are highlighted as errors, TagHelper attributes must be well-formed. Any tips? (alpinejs.dev/essentials/events#preventing-default)
x-on:submit.submit.prevent="..." seems to work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.