skip to Main Content

I have a model class as such:

public class DataModel
{   
    public bool Display { get; set; }
}

I am posting the value from a checkbox after deserializing a FormData object to a JSON object, like this:

this.FormToJSON = form => {
    const json = {};

    new FormData(form).forEach((value, key) => {
      // Ignore the Anti-Forgery Token
      if (key !== "__RequestVerificationToken") {
        json[key] = value;
      }
    });

    return json;
}

The handler over at the page looks like this:

public IActionResult OnPostSave([FromBody] DataModel model)
{
    // Do some stuff
}

The Display property is bound to an input of type checkbox, so when its value of "true" is trying to be deserialized at the Page Handler, this obviously fails and my model parameter ends up being null.

The fix for this would be simple, instead of:

json[key] = value;

I could just write

json[key] = JSON.parse(value);

The only problem is, if I submit a text field that has a value of "true", it gets converted to a boolean, which is obviously not what I want.

Is there a good/better way of doing this? I want to be able to do all my calls in AJAX, because I want to handle the response on the front end i.e if it failed, show a dialog etc. (do not want to use jquery)

2

Answers


  1. Chosen as BEST ANSWER

    I got this to work!

    I'm now converting the form into a request like so

    fetch(pageHandlerURL, {
      method: "POST",
      body: new URLSearchParams(new FormData(formElement))
    }).then(response => {
      // handle response
    });
    

    And on my page handler, it's been slightly changed to this

    public IActionResult OnPostSave([FromForm] DataModel model)
    {
        // Do some stuff
    }
    

  2. C# Razor Pages sending checkbox values in AJAX

    Do you want to use data: $('#idForm').serialize(), ?

    @Html.AntiForgeryToken()
    <form id="idForm"> 
     <input asp-for="Display"  />
             
     <input type="submit" value="submit" id="sub" />
    </form>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {    
            // this is the id of the form
            $("#idForm").submit(function (e) {
               e.preventDefault(); // avoid to execute the actual submit of the form.
    
               
                $.ajax({
                    type: "POST",
                    url: "/checkboxvalue?handler=Save",
                    data: $('#idForm').serialize(),
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                   
                    success: function (data) {
                        alert("success"); // show response 
                    },
                    failure: function (response) {
                        alert(response);
                    }
                });
    
            });
            });
    </script>
    

    And remove [FromBody]

    public IActionResult OnPostSave(DataModel model)
    {
        // Do some stuff
    }
    

    To add below in the pagemodel:

     public bool Display { get; set; }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search