Home > Software design >  Unable Razor post data to api controller via fetch or ajax problem
Unable Razor post data to api controller via fetch or ajax problem

Time:01-04

I have make a simple razor web project and define as below: in program.cs I have add

builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

In the controller, I have make this:

[Route("/api/[controller]")]
[ApiController]

public class BookController : ControllerBase
{

    [HttpPost("SimplePost")]
    public IActionResult SimplePost([FromForm] BookEntry entry)
    {
        var result = entry;
        return Ok();
    }

}

and class is like this:

public class BookEntry
{
    public int BookId { get; set; }
    public string BookName { get; set; } = string.Empty;
}

and then the view page ,

@Html.AntiForgeryToken()
    <form id="bookform">
                    <div >
                        <div >
                            <label for="BookId" >Book Id</label>
                            <input type="text" name="BookId"  />
                        </div>
                        <div >
                            <label for="BookName" >Book Name</label>
                            <input type="text" name="BookName"  />
                        </div>
                    </div>
                </form>
                <div >
                    <div >
                        <div >
                            <button  id="search__btn"><i ></i>Post Buton A</button>
                        </div>
                    </div>
                     <div >
                        <div >
                            <button  id="search__btn2"><i ></i>Post Buton B</button>
                        </div>
                    </div>
                </div>

Where I create the two button, so the javascript, I have write below :

 <script>
        $(function () {
            var url = "/api/book/simplepost";
            $("#search__btn").click(function (e) {
                var formData = $("#bookform").serialize();
                fetch(url, {
                    method: "POST",
                    body: formData,
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
                })
                    .then(response => console.log("done"))
            });
             $("#search__btn2").click(function (e) {
                var formData2 = $("#bookform").serialize();
                $.ajax({
                    url: url,
                    type: "POST",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    headers:
                    {
                        "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
                    },
                    data: formData2,
                    success: function (result, status, xhr) {
                        console.log(`success`);
                    },
                    error: function (xhr, status, error) {
                       console.log(`error`);
                    }
                }).always(function () {
                    console.log(`always done`);
                });

            });
        });
    </script>

When I click the Post Buton A which is use fetch , it can go to simplepost function, but the entry parameter inside is empty when I click the Post Buton B the console page have appear error 400 but I have add header but it still not working.

Can I know how to fix inside ?

Thank you

CodePudding user response:

Try to pass data with query:

 $("#search__btn").click(function (e) {
                var formData = $("#bookform").serialize();
                fetch(url "?" formData , {
                    method: "POST",
                })
                    .then(response => console.log("done"))
            });

action:

[HttpPost("SimplePost")]
    public IActionResult SimplePost(BookEntry entry)
    {
        var result = entry;
        return Ok();
    }

CodePudding user response:

You probably created a ASP.NET Core Web App with which the auto generated code will not map the controllers in your program.cs file. Your code is ok so the only thing you have to do is to add the following line in your program.cs.

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();   // this line

app.Run();
  • Related