Search code examples
c#asp.net-mvcsweetalert2

How to use JScript Promises in an MVC project


I am currently using SweetAlert in my MVC project and it works fine. However, I need to add some radio buttons to it. This feature seems to be part of SweetAlert Version 2.

Now if I do the following without the word await:

   function SampleCode() {
        var formValues = await swal.fire({
            title: 'Multiple inputs',
            html:
                '<input id="swal-input1">' +
                '<input type="checkbox" id="swal-input2" class="swal2-input">',
            focusConfirm: false,
            preConfirm: () => {
                return [
                    document.getElementById('swal-input1').value,
                    document.getElementById('swal-input2').value
                ];
            }
        });

        //Swal.fire(JSON.stringify(formValues));
    }

Then the dialog does pop up. But if I uncomment the second SweetAlert, of course it won't work as I need to make a use of promises. How do I do that in the above function which is in a .cshtml file in an MVC project? Thanks for any help.


Solution

  • From the documentation (the section which says "Multiple inputs aren't supported, you can achieve them by using html and preConfirm parameters..."), here's a CodePen showing something closer to what I think you might be trying to do. Looks like you forgot to declare the outer function as being async, which probably is the reason for your error: https://codepen.io/anon/pen/gyNYep?&editable=true

    For reference, the JavaScript needs to look like this:

    (async function getFormValues () {
    const {value: formValues} = await Swal.fire({
      title: 'Multiple inputs',
      html:
        '<input id="swal-input1" class="swal2-input">' +
        '<input id="swal-input2" class="swal2-input">',
      focusConfirm: false,
      preConfirm: () => {
        return [
          document.getElementById('swal-input1').value,
          document.getElementById('swal-input2').value
        ]
      }
    })
    
    if (formValues) {
      Swal.fire(JSON.stringify(formValues))
    }
    })()