skip to Main Content

I am trying to submit data into a controller method, in order to add the item to a repo.

I am doing this from a HTML (razor) page using AJAX jQuery.

The form serialises the data, and can read the elements. However, as that data is sent to the method, the argument passed into the method is null.

I have gone through a number of posts here on stackoverflow and the internet.

I originally had the controller function as returning an IActionResult and an Action result. Returning the View(); however, the argument was still null.

I have tried to have the argument be the object itself, that being (Book book) such is the model. But to no avail.

The form is serialized and will display in the console:

"ISBN=9780132350884&Title=gg&Author=gg&AvailabilityStatus=true&AvailabilityStatus=false"

I am clearly missing something here.

Thanks in advance.

.cshtml / jQuery:

@model Library.Models.Book

@{
    ViewData["Title"] = "BookAddView";
}

<h1>BookAddView</h1>

<h4>Book</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form id="frm_newBook">
            <div class="mb-3 form-group">
                <label asp-for="ISBN" class="control-label"></label>
                <input asp-for="ISBN" class="form-control" id="input_isbn"/>
            </div>
            <div class="mb-3 form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" id="input_title" />
            </div>
            <div class="mb-3 form-group">
                <label asp-for="Author" class="control-label"></label>
                <input asp-for="Author" class="form-control" id="input_author" />
            </div>
            <div class="form-group form-check mb-3">
                <label class="form-check-label">
                    <input class="form-check-input" asp-for="AvailabilityStatus" id="input_avail" /> @Html.DisplayNameFor(model => model.AvailabilityStatus)
                </label>
            </div>
            <div class="form-group">
                <button id="btn_SubmitBook" class="btn btn-primary">Submit</button>
            </div>
        </form>

    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

<script type="text/javascript">
    $('#btn_SubmitBook').click(
        function () {

            var data = $("#frm_newBook").serialize();

            $.ajax({
                url: '@Url.Action("BookAdd", "Library")',
                type: 'POST',
                dataType: 'json',
                content: "application/json; charset=utf-8",
                data: data
            });
        }
    );
</script>

C# controller:

// POST : Book/Create and AddBook
[HttpPost]
public JsonResult BookAdd(string jsonInput)
{
    if (String.IsNullOrEmpty(jsonInput))
    {
        return Json(0);
    };

    Book book = JsonConvert.DeserializeObject<Book>(jsonInput);

    _bookRepository.AddBook(book);
    return Json(1);
}

2

Answers


  1. Make the following changes in your code:

    1. Specify contentType: 'application/x-www-form-urlencoded; charset=utf-8'. Actually this is the default value.

    When sending data to the server, use this content type. Default is
    "application/x-www-form-urlencoded; charset=UTF-8", which is fine for
    most cases

    1. Set the parameter name according to the parameter name in the controller method: jsonInput
    $.ajax({
        url: '@Url.Action("BookAdd", "Library")',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',                
        data: { jsonInput: data }
       });
    
    Login or Signup to reply.
  2. Value that you have posted:

    ISBN=9780132350884&Title=gg&Author=gg&AvailabilityStatus=true&AvailabilityStatus=false

    does not seem like a valid JSON and I guess that could be the case.

    Also your C# method does not specify from where to take the jsonInput parameter value. Try adding FromBody attribute to the parameter:

    public JsonResult BookAdd([FromBody] string jsonInput)
    

    In order to verify value that is sent to the backend, go to browser’s devtools and see in Netowrk tab if what values are being sent in the request:

    enter image description here

    I can suggest something, that produces correct JSON, if that’s the case:

    var data = new FormData($("#frm_newBook"))
    var json = JSON.stringify(Object.fromEntries(data))
    
    $.ajax({
      url: '@Url.Action("BookAdd", "Library")',
      type: 'POST',
      dataType: 'json',
      content: "application/json; charset=utf-8",
      data: json
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search