ajax post mvc 核心控制器方法中的数据为空

ajax post data null in mvc core controller method

我在这里遇到了这个问题,但我无法解决。我进行了很多搜索,并尝试了在类似 post 上找到的所有解决方案。所以如果对我的案子有任何帮助。我在我的应用程序中发现了问题,首先这是我的观点,当我选择一个类别时,我有类别下拉菜单,我将在 table.[=15 中加载该值的 属性 =]

@model Demo.Models.ViewModel.DeviceVM

<form method="post">

    <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>

                @*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>


                <div class="form-group row">
                    <div class="col-4">
                        <label>Category Properties</label>
                    </div>
                    <div class="col-8">
                        <table class="table table-bordered table-striped">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Property</th>
                                    <th>Value</th>
                                </tr>
                            </thead>
                            <tbody id="plist">

                            </tbody>
                        </table>
                        
                    </div>
                </div>



                @*Seventh 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" />
                        </div>

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

                </div>

            </div>

        </div>
    </div>
</form>

@section Scripts
{
   
    <script>

        $(function ()
        {

            $('#CategoryList').on("change", function () {
                var _category = $('#CategoryList').val();
                var obj = {CategoryID:_category};
                AjaxCall("GetCategoryProperty", JSON.stringify(obj), 'POST').done(function (response) {
                    console.log(JSON.stringify(obj));
                    if (response.length > 0)
                    {
                        console.log("i'm here ");
                    }
                }).fail(function (error) {
                    alert(error.StatusText);
                });                
            });

        });

        function AjaxCall(url, data, type) {
            return $.ajax({
                url: url,
                type: type ,
                data: data ,
                contentType: 'application/json; charset=utf-8',
                dataType:'json'
            });
        }
    </script>

}

这是我的类别模型

public class Category
{
    [Key]
    public int ID { get; set; }

    [Required,MaxLength(15),Display(Name ="Category Name")]
    public string CatName { get; set; }

    public virtual ICollection<Category_Property> categoryprperties {get;set;}

}

这是我在视图中的函数,它的参数总是接收到 0

    [HttpPost]
    public JsonResult GetCategoryProperty([FromBody]int CategoryID)
    {
        DeviceVM obj = new DeviceVM();

        var _CategoryProperty = (from cp in _db.Category_Property
                                 join p in _db.Property on cp.PropertyID equals p.ID
                                 where cp.CategoryID == CategoryID
                                 select new { cp.CategoryID, p.Description, cp.PropertyID });



        return Json(_CategoryProperty );
    }

我在浏览器中打开了检查,但它没有到达 if 块内的消息,因为 ajax 总是为类别 ID 发送 0,我请求帮助以开始工作。

有两种方法可以满足您的要求。

第一种方式你可以post通过如下形式的id:

1.Change JSON.stringify(obj)obj 并删除 contentType: 'application/json; charset=utf-8',:

$(function ()
{
    $('#CategoryList').on("change", function () {
        var _category = $('#CategoryList').val();
        var obj = {CategoryID:_category};     
                                           //change here...
        AjaxCall("/home/GetCategoryProperty", obj, 'POST').done(function (response) {
            console.log(JSON.stringify(obj));
            if (response.length > 0)
            {
                console.log("i'm here ");
            }
        }).fail(function (error) {
            alert(error.StatusText);
        });                
    });

});

function AjaxCall(url, data, type) {
    return $.ajax({
        url: url,
        type: type ,
        data: data ,
        //contentType: 'application/json; charset=utf-8',
        dataType:'json'
    });
}

2.Remove [FromBody] 或添加 [FromForm]:

public class HomeController : Controller
{
    [HttpPost]
    public JsonResult GetCategoryProperty(int CategoryID)
    {
         //...
    }
}

第二种方式你可以post body,你需要像下面这样创建一个模型然后保留你的js代码:

public class Test
{
    public int CategoryID { get; set; }
}

更改您的操作:

public class HomeController : Controller
{
    
    [HttpPost]
    public JsonResult GetCategoryProperty([FromBody] TestM model)
    {
        //...
    }
}