Home > Software design >  Error 415 Insert data into database and update data using jQuery AJAX in ASP.NET 6.0 MVC Application
Error 415 Insert data into database and update data using jQuery AJAX in ASP.NET 6.0 MVC Application

Time:10-09

I made the Add/Edit action for category in my project. I want to do modal (pop-up), so I need to transfer the data to the back side (controller) without refreshing the page. For this reason, I chose to use ajax, but I have a problem again. When i transfered the data to the back side (controller) there isnt problem but in the client side i have 415 error.

Here my Category Controller.

[HttpPost]
    public IActionResult Save([FromBody]CategoryViewModel formData)
    {
        var categoryDto = new CategoryDto
        {
            Id = formData.Id,
            CategoryName = formData.CategoryName
        };

        if (formData.Id == 0)
        {
            var response = _categoryService.AddCategory(categoryDto);

            if (response.IsSucceed)
                return Json(new { @Success = true });

            else
            {
                ViewBag.ErrorMessage = response.Message;
                return Json(new { @Success = false });
            }
        }
        else
        {
            _categoryService.EditCategory(categoryDto);
            return Json(new { @Success = true });
        }
    }
    public IActionResult Edit(int id)
    {
        var category = _categoryService.GetCategoryById(id);

        var viewModel = new CategoryViewModel()
        {
            Id = category.Id,
            CategoryName = category.CategoryName
        };

        return View("Form", viewModel);
    }

Here my modal(pop-up). I use partial

@model CategoryViewModel
<div >

    <div >

        <div >
            <p></p>
            <h4 >@(Model.Id == 0 ? "Add Category" : "Edit Category")</h4>
            <button id="btnHideCategoryModal" type="button"  data-dismiss="modal">
                <i ></i>
            </button>
        </div>

        <div >
            <form asp-area="Admin" asp-controller="Category" asp-action="Save" method="post">
                <div >
                    <input asp-for="CategoryName"  type="text"
                           placeholder="Category Name" id="@(Model.Id == 0 ? "inputAddCategory" : "inputEditCategory")" />
                </div>
                
                <input id="@(Model.Id == 0 ? "btnAddCategory" : "btnEditCategory")" type="submit"  value="@(Model.Id == 0 ? "Add Category" : "Update")" />
            </form>

        </div>

    </div>

</div>

Here my Ajax Code

$('#btnAddCategory').click(function () {

        var category = {
            CategoryName: $('#inputAddCategory').val(),
        };

        $.ajax({
            type: 'Post',
            url: '/Admin/Category/Save',
            data: JSON.stringify(category),
            contentType: 'application/json; charset=utf-8;',
            dataType: 'json',
            success: function () {
                location.reload(true);
            }
        });
    });
    $('#btnEditCategory').click(function () {

        var category = {
            CategoryName: $('#inputEditCategory').val(),
        };

        $.ajax({
            type: 'Post',
            url: '/Admin/Category/Edit',
            data: JSON.stringify(category),
            contentType: 'application/json; charset=utf-8;',
            dataType: 'json',
            success: function () {
                location.reload(true);
                
            }
        });
    });

CodePudding user response:

I solved my problem.

I was sending a post request to action with asp tag helpers on the form, but also post request with ajax. I guess the two conflicted with each other and that's why I got the 415 error. Then i removed the tag helpers in the form and the problem was fixed.

<form>
                <div >
                    <input asp-for="CategoryName"  type="text"
                           placeholder="Category Name" id="@(Model.Id == 0 ? "inputAddCategory" : "inputEditCategory")" />
                </div>

                <button id="@(Model.Id == 0 ? "btnAddCategory" : "btnEditCategory")" type="submit" >@(Model.Id == 0 ? "Add Category" : "Edit Category")</button>
            </form>

CodePudding user response:

Give the form input the name of the property you are sending. Then serialize the form with jQuery serialize().

<form asp-area="Admin" asp-controller="Category" asp-action="Save" method="post">
      <div >
           <input name="CategoryName" asp-for="CategoryName"  type="text"
                           placeholder="Category Name" id="@(Model.Id == 0 ? "inputAddCategory" : "inputEditCategory")" />
      </div>      
      <input id="@(Model.Id == 0 ? "btnAddCategory" : "btnEditCategory")" type="submit"  value="@(Model.Id == 0 ? "Add Category" : "Update")" />
</form>

<script>
$('#btnAddCategory').click(function () {
        const data = $("form").serialize();
        $.ajax({
            type: 'Post',
            url: '/Admin/Category/Save',
            data: data,
            contentType: 'application/json; charset=utf-8;',
            dataType: 'json',
            success: function () {
                location.reload(true);
            }
        });
        return false
});
$('#btnEditCategory').click(function () {
        const data = $("form").serialize();
        $.ajax({
            type: 'Post',
            url: '/Admin/Category/Edit',
            data: data,
            contentType: 'application/json; charset=utf-8;',
            dataType: 'json',
            success: function () {
                location.reload(true);
                
            }
        });
        return false
});
<\script>
  • Related