Filipe Nóbrega
Filipe Nóbrega

Reputation: 667

.Net Core MVC Post parameter binding is null

I have an MVC controller responsible for the Group entity.

My [HttpPost] method handles the creation of a new Group. Inside the parameters I try to bind the request to a simple GroupModel DTO.

The problem is that the parameter is always ´null´. I also added .AddNewtonsoftJson(); to my service collection.

GroupController

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

[HttpPost]
public async Task<IActionResult> Create([FromBody] GroupModel group)
{
    var (result, groupId) = await _groupService.Create(group.Name, group.Roles);

    if (result.Succeeded)
    {
        return View("Index");
    }
    else
    {
        AddErrors(result);
        return Create();
    }
}

GroupModel

public class GroupModel
{
    
    public string Name { get; set; }
    public int[] Roles { get; set; }

}

JS

function create() {

    var group = new Object();
    group.name = getGroupName();
    group.roles = getSelectedRoles();

    /* Ajax request */
    $.ajax({
        url: BASE_URL + 'Group/Create',
        type: 'POST',
        data: JSON.stringify(group),
        dataType: "json",  
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert("success");
        },
        error: function () {
            alert("error");
        }
    });
}

Im totaly sure Im missing something, I've done this countless times but I just cant figure it out.

Thank you.

Upvotes: 1

Views: 352

Answers (1)

Yiyi You
Yiyi You

Reputation: 18179

I think it maybe caused by the data format of group.group.name = getGroupName(); group.roles = getSelectedRoles();I add sample data to it and it worked. Here is a worked demo: GroupController:

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

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] GroupModel group)
        {
            return View();
        }

View:

<button onclick="create()">Create</button>
@section scripts{ 
    <script type="text/javascript">
    function create() {

        var group = new Object();
        group.name = "a";
        group.roles = new Array();
        group.roles[0] = 1;
        group.roles[1] = 2;
    /* Ajax request */
        $.ajax({
            url: 'Create',
            type: 'POST',
            data: JSON.stringify(group),
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                alert("success");
            },
            error: function () {
                alert("error");
            }
        });
        
    }
    </script>
}

Result: enter image description here

Upvotes: 1

Related Questions