3

I'm using Asp.net Core Razor Pages and want to POST some data to server when a button clicked but I cannot get client values in calling method, it is always null:

<button type="button" class="btn btn-primary" onclick="save1()">Submit</button>

my js code:

function save1() {
          var order = { SerialNo: '1'};

            $.ajax({
                type: "POST",
                url: "@Url.Page("Index","Save1")",
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: JSON.stringify(order),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    alert('Success!');
                },
                failure: function (response) {
                    alert('error!');
                }
            });

        }

my page handler:

 public async Task<IActionResult> OnPostSave1Async(CreateOrderViewModel order)
    {
        //some code
    }

and my view model:

public class CreateOrderViewModel
{

    public string SerialNo { get; set; }
    ...
}

1 Answer 1

2

You may need to add [FromBody] to receive the sent value, like this:

Model:

       public class Test {
            public string SerialNo { get; set; }
            }

Controller:

 [HttpPost]
        public IActionResult Index([FromBody]Test order)
        {

            return View();
        }

        public IActionResult Index()
        {
            return View();
        }

View:

<button type="button" class="btn btn-primary" onclick="save1()">Submit</button>
<script>
    function save1() {
        var order = { SerialNo: '1' };

            $.ajax({
                type: "POST",
                url: "test/Index",
                data: JSON.stringify(order),
                contentType: "application/json; charset=utf-8",
               dataType: "json",
                success: function () {
                alert('Success!');
                },
                failure: function (response) {
                alert('error!');
                }
                });

                }
</script>

Result:

enter image description here

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.