Home > Net >  Asp.Net Core: Send object and parameter to mvc controller using ajax?
Asp.Net Core: Send object and parameter to mvc controller using ajax?

Time:06-21

I want to send the form data $('#SearchProduct').serialize() with a parameter to the controller... But whatever I do, only one parameter is sent!!!

Jquery :

 const MainProducts = new Products();
MainProducts.LoadProducts(null, 1);

Search_Btn.click(function () {
    const Form_Data = SearchProduct.serialize();
    MainProducts.LoadProducts(Form_Data, 1);
});

Ajax :

 LoadProducts(ObjSearch, page) {       
console.log(page);
$.ajax({
    url: GetUrlAdmin.Product.AllShowProducts,
    type: "Get",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    data: { ObjSearch, page },
    dataType: 'json',
    contentType: 'application/json;charset=utf-8',
    success: function (result) {
    })

Controller :

 public async Task<JsonResult> GetAllShowProducts(ProductSearchViewModel model, int page)
    {
        var Products = await _admin.GetAllShowProducts(model, page);

        return Json(new { data = Products });

    }

I also tested the following code, but it was not sent again?

JSON.stringify(ObjSearch, page)

CodePudding user response:

I want to send the form data $('#SearchProduct').serialize() with a parameter to the controller... But whatever I do, only one parameter is sent!!!

The issue might be relating to the form elements, when binding the form element and property, we need to bind it via the page model. You can refer to the following sample code (using VS 2022 and Asp.net 6 MVC) and then compare with your code.

Model:

public class Product
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string UrlImage { get; set; }
    public string Detail { get; set; }
    public decimal Price { get; set; }
}

Home controller:

    public IActionResult ProductCreate()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult ProductCreate(Product product)
    {
        return View();
    }

ProductCreate.cshtml:

@model MVCWebApp.Models.Product

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

<h1>ProductCreate</h1>

<h4>Product</h4>
<hr />
<div >
    <div >
        <form id="formprodcreate" asp-action="ProductCreate">
            <div asp-validation-summary="ModelOnly" ></div>
            <div >
                <label asp-for="Id" ></label>
                <input asp-for="Id"  />
                <span asp-validation-for="Id" ></span>
            </div>
            <div >
                <label asp-for="Title" ></label>
                <input asp-for="Title"  />
                <span asp-validation-for="Title" ></span>
            </div>
            <div >
                <label asp-for="UrlImage" ></label>
                <input asp-for="UrlImage"  />
                <span asp-validation-for="UrlImage" ></span>
            </div>
            <div >
                <label asp-for="Detail" ></label>
                <input asp-for="Detail"  />
                <span asp-validation-for="Detail" ></span>
            </div>
            <div >
                <label asp-for="Price" ></label>
                <input asp-for="Price"  />
                <span asp-validation-for="Price" ></span>
            </div>
            <div >
                <input type="submit" value="Create"  /> 
                <input type="button"  id="btnFormSubmit" value="Form Ajax Submit"/> 
                <input type="button"  id="btnSubmit" value="Ajax Submit"/>
            </div>
        </form>
    </div>
</div>

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

Js code: [Note] In the Ajax function, there is no need to set the datatype and contenttype.

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(function(){
            //use the serialize method to serialize the form.
            $("#btnFormSubmit").click(function(){
                $.ajax({
                    url: "/Home/ProductCreate",
                    type: "Post",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data: $('#formprodcreate').serialize(), 
                    success: function (result) {
                    }
                 });
            });
            //create a JS object and get the entered value, then transfer the object to the controller.
            $("#btnSubmit").click(function(){
                var product = {};
                product.Id = $("input[name='Id']").val();
                product.Title = $("input[name='Title']").val();
                product.UrlImage = $("input[name='UrlImage']").val();
                product.Detail = $("input[name='Detail']").val();
                product.Price = $("input[name='Price']").val();

                $.ajax({
                    url: "/Home/ProductCreate",
                    type: "Post",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data: product, 
                    success: function (result) {
                    }
                 });
            });
        });
    </script>
}

The output is like this: enter image description here

CodePudding user response:

You can send the data to the controller as object and then serialize it.

Example Controller

public object GetAllShowProducts(object value) 
{
    var dataString = JsonConvert.SerializeObject(value);
    _YourModel data = JsonConvert.DeserializeObject<_YourModel>(dataString);
}

Example Ajax Metod

let _YourObject= [{ Username: "test", Password: "123" }];

postAjaxData("_YourControllerPath", _YourObject)

function postAjaxData(pageurl, dataString) {
    let paramaters = JSON.stringify({ value: dataString });
    return JSON.parse($.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: pageurl,
        data: paramaters,
        datatype: "json",
        async: false
    }).responseText);
}
  • Related