Click here to Skip to main content
15,347,207 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
hello,

I was trying to send a view model to a controller using ajax .but it always gives my null, I searched but no luck , so if you can help me here

this my viewmodel:
public class DeviceVM
    {
        public Device device { get; set; }
        public IEnumerable<SelectListItem> CategoryDropDown { get; set; }
        public IEnumerable<SelectListItem> UserDropDown { get; set; }
        public IList<CheckBoxItem> AvailableCatProperty { get; set; }
    }


I just want to fill the AvaliableCatProperty list of model to pass it to the controller using ajax

here my ajax call :
$(function ()
{
    $('#btnsave').on("click", function () {

        $('#mytable tbody tr').each(function ()
        {
            var txtid = $(this).find('td').eq(0).text();
            var txttitle = $(this).find('td').eq(1).text();
            var txtvalue = $(this).find('td').eq(2).find('input').val();

            var properties =
            {
                'ID': txtid,
                'Title': txttitle,
                'Value':txtvalue
            };


        });
        console.log(prop);
        $.ajax({
            url: '/Home/Create',
            type: 'POST',
            data:
            {
                vm:{AvailableCatProperty:properties},
                d:{}
            }
        });
    });



});


here is my CheckBoxItem model:

public class CheckBoxItem
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public bool IsChecked { get; set; }
        public string Value { get; set; }
    }


here is my controller :

public IActionResult Create(DeviceVM vm,Device d)
        {
            return View();

        }


here is my view :

@model LinkedGates.Models.ViewModel.DeviceVM


<form method="post" id="myform">

    <input hidden asp-for="@Model.device.ID" />

    <div class="border p-3">

        @*putting the page label*@
        <div class="row">
            <h3 class="text-info pl-3 pb-3">Create Device</h3>
        </div>


        @*putting all the fields (label & Textbox) as a rows *@
        <div class="row">

            @*will fill in each row till the column 8*@
            <div class="col-8">


                @*First Row => Device Name*@
                <div class="form-group row">

                    @*field Label*@
                    <div class="col-4">
                        <label asp-for="@Model.device.DeviceName"></label>
                    </div>

                    @*field Text*@
                    <div class="col-8">
                        <input class="form-control" asp-for="@Model.device.DeviceName" />
                        <span asp-validation-for="@Model.device.DeviceName" class="text-danger"></span>
                    </div>

                </div>


                @*Second Row => Serial No*@
                <div class="form-group row">

                    @*field Label*@
                    <div class="col-4">
                        <label asp-for="@Model.device.SerialNo"></label>
                    </div>

                    @*field Text*@
                    <div class="col-8">
                        <input class="form-control" asp-for="@Model.device.SerialNo" />
                        <span asp-validation-for="@Model.device.SerialNo" class="text-danger"></span>
                    </div>

                </div>


                @*Third Row => Acquistion Date*@
                <div class="form-group row">

                    @*field Label*@
                    <div class="col-4">
                        <label asp-for="@Model.device.AcquisitionDate"></label>
                    </div>

                    @*field Text*@
                    <div class="col-8">
                        <input class="form-control" asp-for="@Model.device.AcquisitionDate" />
                        <span asp-validation-for="@Model.device.AcquisitionDate" class="text-danger"></span>
                    </div>

                </div>


                @*Forth Row => Memo*@
                <div class="form-group row">

                    @*field Label*@
                    <div class="col-4">
                        <label asp-for="@Model.device.Memo"></label>
                    </div>

                    @*field Text*@
                    <div class="col-8">
                        <input class="form-control" asp-for="@Model.device.Memo" />
                        <span asp-validation-for="@Model.device.Memo" class="text-danger"></span>
                    </div>

                </div>


                @*fifth Row => Category List*@
                <div class="form-group row">

                    @*field Label*@
                    <div class="col-4">
                        <label asp-for="@Model.device.CategoryID"></label>
                    </div>

                    @*field Text*@
                    <div class="col-8">

                        <select asp-for="@Model.device.CategoryID" asp-items="@Model.CategoryDropDown" class="form-control"
                                id="CategoryList" >
                            <option value="">-- Select Category --</option>
                        </select>
                        <span asp-validation-for="@Model.device.CategoryID" class="text-danger"></span>
                    </div>
                </div>

                @*sixth Row => the category properties*@
                <div class="form-group row">
                    <div class="col-4">
                        <label>Category Properties</label>
                    </div>
                    <div class="col-8" id="catprop">
                      
                        @*will show the properties of the selected category *@
                    </div>
                </div>

                @*Seventh Row => User List*@
                <div class="form-group row">

                    @*field Label*@
                    <div class="col-4">
                        <label asp-for="@Model.device.UserID"></label>
                    </div>

                    @*field Text*@
                    <div class="col-8">
                        <select asp-for="@Model.device.UserID" asp-items="@Model.UserDropDown" class="form-control">
                            <option disabled selected value="">-- Select Category --</option>
                        </select>
                        <span asp-validation-for="@Model.device.UserID" class="text-danger"></span>
                    </div>

                </div>


                @* Eighth Row => Buttons*@
                <div class="form-group">

                    <div class="col-8 offset-4 row">

                        @*Save Button*@
                        <div class="col">
                            <input type="submit" value="Save" asp-action="Create" class="btn btn-info w-100" id="btnsave"/>
                        </div>

                        @*Back Button*@
                        <div class="col">
                            <a class="btn btn-success w-100" asp-action="Index">Back</a>
                        </div>
                    </div>

                </div>

            </div>

        </div>


What I have tried:

I tried a lot to find a solution but no hope , the action parameter ( the viewmodel ) return with null value
Posted
Updated 7-Feb-22 21:48pm
v2

1 solution

Quote:
JavaScript
$('#mytable tbody tr').each(function ()
{
    var txtid = $(this).find('td').eq(0).text();
    var txttitle = $(this).find('td').eq(1).text();
    var txtvalue = $(this).find('td').eq(2).find('input').val();

    var properties =
    {
        'ID': txtid,
        'Title': txttitle,
        'Value':txtvalue
    };
});

console.log(prop);

$.ajax({
    url: '/Home/Create',
    type: 'POST',
    data:
    {
        vm: { AvailableCatProperty: properties },
Your each callback creates a local variable called properties, which will not be available outside of that function.

Outside of that function, you then log an unrelated and apparently undefined variable called prop.

Also outside of that function, you try to send a variable called properties in your AJAX request. But since you're not in the same function where that variable was declared, it is not defined.

You need to work out what format the data needs to be sent as. For example, to send an array of objects:
JavaScript
let properties = [];

$('#mytable tbody tr').each(function () {
    const txtid = $(this).find('td').eq(0).text();
    const txttitle = $(this).find('td').eq(1).text();
    const txtvalue = $(this).find('td').eq(2).find('input').val();

    const item = {
        'ID': txtid,
        'Title': txttitle,
        'Value':txtvalue
    };
    
    properties.push(item);
});

console.log(properties);

$.ajax({
    url: '/Home/Create',
    type: 'POST',
    data: {
        vm: { AvailableCatProperty: properties },
   
Comments
Ramy82 8-Feb-22 13:48pm
   
Mr. Richard , glad for your help . I tried your solution but still i get null in the create action method and i get in the console when i click the save button (failed to load resources 400). any suggestions ?
Richard Deeming 9-Feb-22 4:04am
   
You need to check that the URL is correct, and that the data you're sending matches the format expected by the server.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900