locked
Problem with binding model to controller RRS feed

  • Question

  • User456264971 posted

    Hi guys! I need help, I have a problem with binding model to controller. I'm try to explain more detail. I trying to POST data via AJAX to controller and get error that my model is empty. I can't understand the reason of it. If I open a console of browser I see that all parameters are passed, but controller doesn't get it. Thank you.

    JS:

    <script type="text/javascript">
            var url, row;        
     
            function editCustomer() {
                row = $('#dg_customers').datagrid('getSelected');
                if (row) {
                    $('#new_customer').dialog('open').dialog('center').dialog('setTitle', 'Edit customer');
                    $('#fm').form('load', row);
                    url = '/Home/EditCustomer/';
                }
            }
    
            function saveCustomer() {                      
                msg = JSON.stringify({ 'Id': row.Id, 'Name': $('#Name').textbox('getValue'), 'Address': $('#Address').textbox('getValue'), 'Email': $('#Email').textbox('getValue'), 'Notes': $('#Notes').textbox('getValue') });
                                      
                $.ajax({
                    type: "POST",
                    url: url,
    
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
    
                    data: msg,
                    contentType: "application/json",
                    traditional: true,
                    dataType: "json",
                    success: function (res) {
                        $.messager.alert('Information', res.text, 'info');
                        if (res.text == "Customer added successfully!") {
                            $('#fm').form('clear'); $('#new_customer').dialog('close');
                            $('#dg_customers').datagrid('reload');
                        }
                        if (res.text == "Customer edited successfully!") {
                            $('#fm').form('clear'); $('#new_customer').dialog('close');
                            $('#dg_customers').datagrid('reload');
                        }
    
                    }, error: function () { alert("Did not work"); }
                });
            }
    
        </script>

    Model:

    public class Customer
        {
            public int Id { get; set; }
            [Required]
            [StringLength(20, MinimumLength = 3, ErrorMessage = "Length of name can be between 3 and 20 symbols.")]
            public string Name { get; set; }
    
            [StringLength(200, ErrorMessage = "Length of address can't be more than 200 symbols.")]
            public string Address { get; set; }
    
            [Required]
            [EmailAddress(ErrorMessage = "Incorrect Email.")]
            public string Email { get; set; }
    
            [StringLength(1000, ErrorMessage = "Length of notes can't be more than 1000 symbols.")]
            public string Notes { get; set; }
            public bool IsBlocked { get; set; }
            public DateTime Datetime_create { get; set; }
        }

    Controller:

            [Authorize]
            [HttpPost]
            [ValidateAntiForgeryToken]
            public JsonResult EditCustomer([FromBody] Customer customer)
            {
                if (ModelState.IsValid)
                {
                    cdb.EditCustomer(customer);
                    return new JsonResult(new { text = "Customer edited successfully!" });           
                }
                else
                {
                    return new JsonResult(new { text = "Not all data valid!" });
                }
            }

    View:

    @{
        ViewData["Title"] = "List of customers";
    }
    @Html.AntiForgeryToken()
    
    <table id="dg_customers" title="Customers" class="easyui-datagrid" style="width:100%;height:100%"
           method="get"
           url="/Home/GetCustomers"
           toolbar="#toolbar"
           rownumbers="true" fitColumns="true" singleSelect="true" pagination="true" sortName="Name" sortOrder="asc" idField="Id" striped=true>
    
        <thead>
            <tr>
                <th field="Id" width="15" hidden="true">ID1</th>
                <th field="Name" width="150" sortable="true">Name</th>
                <th field="Address" width="60" sortable="true">Address</th>
                <th field="Email" width="60">Email</th>
                <th field="Notes" width="15" hidden="true">Notes</th>
                <th field="IsBlocked" width="60" sortable="true">Blocked</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newCustomer()">Add Customer</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editCustomer()">Edit Customer</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="delCustomer()">Delete Customer</a>
    </div>
    
    <div id="new_customer" class="easyui-dialog" style="width:500px;height:620px;padding:10px 1px;"
         closed="true" buttons="#dlg-buttons" data-options="openDuration:400, closeDuration:400, closeAnimation:'fade', openAnimation:'fade'">
        <div class="ftitle">Add new customer</div>
    <form id="fm"> <div class="fitem"> <label>Customer's name:</label> <input id="Name" name="Name" class="easyui-textbox" required missingMessage="This field must be filled."> </div> <div class="fitem"> <label>Customer's address:</label> <input id="Address" name="Address" class="easyui-textbox"> </div> <div class="fitem"> <label>Customer's email:</label> <input id="Email" name="Email" class="easyui-textbox" required missingMessage="This field must be filled."> </div> <div class="fitem"> <label>Notes:</label> <input id="Notes" name="Notes" class="easyui-textbox" data-options="multiline:true" style="height:100px"> </div> </form> </div> <div id="dlg-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveCustomer()" style="width:100px">Ok</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#new_customer').dialog('close')" style="width:90px">Cancel</a> </div>

    After running my project I see such error:

    System.NullReferenceException: 'Object reference not set to an instance of an object.'

    customer was null.

    Wednesday, November 18, 2020 7:46 AM

All replies

  • User1312693872 posted

    Hi,Soi13

    System.NullReferenceException: 'Object reference not set to an instance of an object.'

    customer was null.

    Many reasons will lead to this error, you can use this link to check your code.

    And when you met this error? I checked your edit js but can't find anything wrong, and I can not check your GetCustomer() method in controller,

    can you share that part of code to us?

    Best Regards,

    Jerry Cai

    Thursday, November 19, 2020 7:12 AM