Model is Null while passing by Ajax Call MVC?

柔情痞子 提交于 2021-02-19 05:27:52

问题


I am new bird in MVC. I want to pass the Model into the Ajax call, i write the following code to do so. But it always passing NULL to all properties.

   $("#btnsubmit").click(function () {

        alert('hello');
        var productModel = {
            Name: 'ram@mailinator.com',
            Address: "Chai"

        };
        $.ajax({
            type: "POST",
            url: '@Url.Action("ContactDistributor", "AjaxCallTest")',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ model: productModel }),

            dataType: "json",
            success: function () { alert('Success'); },
            error: function (xhr) {
                alert(xhr.error);
            }
        });
        return false;

    });

MODEL :

    public class AjaxCalltestModal
{
    public int Id { get; set; }
    public String Name { get; set; }
    public String Address { get; set; }

}

Controller :

        [HttpPost]
    public ActionResult ContactDistributor(WebApplication1.Models.AjaxCalltestModal a)
    {
        return Json("test");
    }

Please help me.


回答1:


I have resolved the Issue by using the following Code:

$("#btnsubmit").click(function () {

    alert('hello');
    var productModel = {
        Name: 'ram@mailinator.com',
        Address: "Chai"

    };
    $.ajax({
        type: "POST",
        url: '@Url.Action("ContactDistributor", "AjaxCallTest")',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ 'model': productModel }),

        dataType: "json",
        success: function () { alert('Success'); },
        error: function (xhr) {
            alert(xhr.error);
        }
    });
    return false;

});

Thanks for your efforts and comments..




回答2:


JSON.stringify({ model: productModel })

should be

JSON.stringify(productModel)



回答3:


most probably setting data as a Javascript object will work instead of tyring to Stringify it. Because as far as i know, query ajax method already does this for you

data:  productModel 



回答4:


Old question, but this might help someone in the future. If you have a property in your model called "Model", the MVC parser doesn't seem to process it properly and it will also come back null.

Just rename it to anything else and it works properly.



来源:https://stackoverflow.com/questions/33034420/model-is-null-while-passing-by-ajax-call-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!