Home > Enterprise >  Ajax Post with Razor Pages
Ajax Post with Razor Pages

Time:10-29

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; }
    ...
}

CodePudding user response:

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

  • Related