skip to Main Content

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 class="modal-dialog modal-dialog-centered">

    <div class="modal-content">

        <div class="modal-header">
            <p></p>
            <h4 class="modal-title ms-4">@(Model.Id == 0 ? "Add Category" : "Edit Category")</h4>
            <button id="btnHideCategoryModal" type="button" class="close" data-dismiss="modal">
                <i class="fa-solid fa-xmark fa-xl close"></i>
            </button>
        </div>

        <div class="modal-body">
            <form asp-area="Admin" asp-controller="Category" asp-action="Save" method="post">
                <div class="form-group mb-3">
                    <input asp-for="CategoryName" class="form-control" type="text"
                           placeholder="Category Name" id="@(Model.Id == 0 ? "inputAddCategory" : "inputEditCategory")" />
                </div>
                
                <input id="@(Model.Id == 0 ? "btnAddCategory" : "btnEditCategory")" type="submit" class="btn btn-primary form-control" 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);
                
            }
        });
    });

2

Answers


  1. Chosen as BEST ANSWER

    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 class="form-group mb-3">
             <input asp-for="CategoryName" class="form-control" type="text"
                  placeholder="Category Name" id="@(Model.Id == 0 ? 
                  "inputAddCategory" : "inputEditCategory")" />
         </div>
    
         <button id="@(Model.Id == 0 ? "btnAddCategory" : "btnEditCategory")" 
                 type="submit" class="btn btn-primary form-control">
                 @(Model.Id == 0 ? "Add Category" : "Edit Category")
         </button>
      </form>
    

  2. 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 class="form-group mb-3">
               <input name="CategoryName" asp-for="CategoryName" class="form-control" type="text"
                               placeholder="Category Name" id="@(Model.Id == 0 ? "inputAddCategory" : "inputEditCategory")" />
          </div>      
          <input id="@(Model.Id == 0 ? "btnAddCategory" : "btnEditCategory")" type="submit" class="btn btn-primary form-control" 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search