Home > Software design >  Alpine Expression Error: createFormComponent is not defined
Alpine Expression Error: createFormComponent is not defined

Time:12-12

I am using Alpine JS in .NET Core 6 MVC project. I have loaded the alpine js file from https://unpkg.com/[email protected]/dist/cdn.min.js. I then added the following code in the Home/Index.cshtml file.

<form id="myForm"
  x-data="createFormComponent()" 
  x-on:submit.prevent="onSubmit">

  <input id="email" type="text" name="email" 
    x-model="email" />

  <span  style="display: none"
    x-show="error"
    x-text="error"
  ></span>

  <button type="submit">Submit</button>
</form>

@section Scripts {

   <script>
  (function () {
    'use strict';

    window.createFormComponent = function () {
      return {
        email: '',
        error: '',

        onSubmit($event) {
          this.error = !this.email 
            ? 'You must enter an email address' 
            : '';
        },
      };
    };
  })();
</script>

}

But when I access the page in the browser, it always throws the error "Alpine Expression Error: createFormComponent is not defined". I have tried to put it into a js file and load it. Also tried to define the component in alpine:init event. None of them worked. The same code works in plain html file served from IIS. I am not sure what is wrong here. Can anyone please help.

CodePudding user response:

Be sure add js in your _Layout.cshtml or in your current page @section Scripts {...} like below:

<script src="https://unpkg.com/alpinejs" defer></script>

Note: HTML defer attribute must be added.

  • Related