0

I am trying to pass a string of objects from my javascript to the controller. But when I run the code, nothing is passed to the controller, all I get is a null value. I go through debugging and I can see the string of data that should be passed, but it never goes or hits the controller. Here is my code below.

What I want it to pass is the ContactID, Address, ContactName and Phone. When I debug, I can see that it's passing/getting the data, but it doesn't pass to the controller. I have tried doing a string[ ] obj, but I still get a null reference. I am sure I am missing something, and just needing someone to point me in the right direction.

Thanks in Advance!

JavaScript:

  function saveEdit(element) {
    var form = $(element).closest('tr');
    model = retrieveEditCustomerModel(form);
    PostObject("Home/Update", model, replacethisEditRow, element);
}
function retrieveEditCustomerModel(form) {
    var model = new Object();
    model.CompanyID = $(form).find('.customer-stored-id').attr('data-value');
    model.CompanyName = $(form).find('#SelectedCustomer_CompanyName').val();
    model.Address = $(form).find('#SelectedCustomer_Address').val();
    model.ContactName = $(form).find('#SelectedCustomer_ContactName').val();
    model.Phone = $(form).find('#SelectedCustomer_Phone').val();
    return model;
}

function replacethisEditRow(result, element) {
    $(element).closest('tr').replaceWith(result);
}


__________________________________________________________________________
function PostObject(url, object, callback, param1, param2, errorCallback) {
    var data = JSON.stringify(object);
    $.ajax({
        url: "../../"+ url ,
        data: data,
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            if (callback != null && callback != undefined) {
                callback(result, param1, param2);
            }
        },
        error: function (result) {
            if (errorCallback != undefined) {
                errorCallback(result.responseText);
            }
            else {
                if (result.responseText != '') {
                    alert(result.responseText);
                }
                else {
                    alert("An error occurred while processing results.  Please consult an administrator.");
                }
            }
        }
    });
}

Controller:

  public ActionResult Update(CustomersViewModel obj)
        {
            using (CustomerEntities db = new CustomerEntities())
        {


      Customer existing =  db.Customers.Find(obj.SelectedCustomer.CustomerID);

            existing.CompanyName = obj.SelectedCustomer.CompanyName;
            existing.Address = obj.SelectedCustomer.Address;
            existing.ContactName = obj.SelectedCustomer.ContactName;
            existing.Phone = obj.SelectedCustomer.Phone;
            db.SaveChanges();

            CustomersViewModel model = new CustomersViewModel();
           model.Customers = db.Customers.OrderBy(m =>   m.CustomerID).Take(5).ToList();

            model.SelectedCustomer = existing;
            model.DisplayMode = "ReadOnly";
            return View("Index", model);
        };
    }  

Adding Class

  public class CustomersViewModel
{
    //This property holds a list of customers to be displayed on the view
    public List<Customer> Customers { get; set; }

    //This property points to a customer that is selected by the user if no customer is selected then it will be null. 
    public Customer SelectedCustomer { get; set; }

    // This property indicates the mode of the customer details area.  Possible values are readonly after selecton.   
    public string DisplayMode { get; set; }
}
4
  • What's the value of obj in your controller? I suspect you have to do the equivalent of JSON.parse on that side, before you can use it like an object. What language is your controller in? Commented Mar 19, 2015 at 20:08
  • @DaveS the language is C# MVC5. I added the Class into the update up top. thought that I should pass the class in as an object, but maybe I am doing that incorrectly. and that is where I am failing? Commented Mar 19, 2015 at 20:38
  • Does obj contain any data that isn't the default? Do you have code in the controller that assigns the values from the posted data string into a Customer instance? Check out @bluetoft 's answer. I think there's a disconnect between what you're sending and what you're expecting. You're sending data that is equivalent to a Customer object, but treating it like it's a CustomersViewModel object. Commented Mar 19, 2015 at 20:56
  • @DaveS I just looked at bluetoft's answer and yes you both are correct. I was treating it like it was a CustomersViewModel. Thank you both! Commented Mar 19, 2015 at 21:28

2 Answers 2

2

You are sending the SelectedCustomer as the entire object in the POST body.

change your function to return { SelectedCustomer: model };

function retrieveEditCustomerModel(form) {
    var model = new Object();
    model.CompanyID = $(form).find('.customer-stored-id').attr('data-value');
    model.CompanyName = $(form).find('#SelectedCustomer_CompanyName').val();
    model.Address = $(form).find('#SelectedCustomer_Address').val();
    model.ContactName = $(form).find('#SelectedCustomer_ContactName').val();
    model.Phone = $(form).find('#SelectedCustomer_Phone').val();
    /* return model; */
    return { SelectedCustomer: model };
}

This will populate the C# Model properly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I added the properties separately then I came back and saw your answer, and that worked perfectly.
0

The reason it can happen is that you havent set attribute [HttpPost] to your controller.

1 Comment

Hi Naragot, I actually do have [HttpPost] as an attribute in my controller, I just didn't place it in the forum

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.