Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

On Ajax call from Angular controller, i am passing a complex object as data. On MVC controller object has all null values. I have MVC view as given below, which will be the boiler plate for Register customer View.

<div data-ng-app="customer" id="customer" data-ng-controller="rootViewModel">
<h2>{{ pageHeading }}</h2>
<hr />
<form id="formElement">
    <div ng-view></div>
</form>

Using AngularJS, I will be loading the register customer view, mark of register customer view given below. I have register customer function tied to button using ng-click directive.

<fieldset class="form-horizontal">
<div class="form-group">
    <label class="control-label col-sm-3">Company Name</label>
    <div class="col-sm-4">
        <input class="form-control inputfieldValidation" ng-model="customer.Name" type="text" placeholder="Full company name" required autofocus />
    </div>
</div>
<div class="form-group">
    <label class="control-label col-sm-3">PAN</label>
    <div class="col-sm-4">
        <input class="form-control" ng-model="customer.Pan" type="text">
    </div>
</div>
<div class="form-group">
    <label class="control-label col-sm-3">TIN</label>
    <div class="col-sm-4">
        <input class="form-control inputfieldValidation" ng-model="customer.Tin" type="text" required />
    </div>
</div>
<button class="btn btn-primary proceedNext" id="registerCompany" ng-click="registerCompany(customer)">Register Customer</button>
</fieldset>

I have angular controller, which has function called registerCustomer() that will be called on click of register customer. I have an ajax call inside that function as given below.

customerModule.controller("CustomerRegistration", function ($scope) {
    var initialize = function () {
    }
    $scope.registerCompany = function (customer) {
        $.ajax({
            url: 'Home/RegisterCompany',//make sure url exist
            data: JSON.stringify({company: customer}),//pass data to action
            type:'POST',
            success: function (data) {
                alert(JSON.stringify(data));
                //window.location.href = '@Url.Action("Order")'; //redirect
            }
        });
    }
    initialize();
});

On MVC, i have a model called Company as given below.

public class Company
{
    public string Name;
    public string Pan;
    public string Tin;
}

and my MVC controller look as

[HttpPost]
public JsonResult RegisterCompany(Company company)
{
    //Do something
    return null;
}

Always I have null object on MVC controller, please help me if am missing anything. Thanks in advance

share|improve this question
    
A few things mixing angular with jquery ajax is not recommended. And if i am not mistaken the default content type supported by MVC is not JSON is x-www-form-urlencoded so another reason for this code to fail – Dalorzo Oct 15 '15 at 18:43
    
This link might help you stackoverflow.com/questions/20384242/… – Mithun Pattankar Oct 15 '15 at 18:45

EDIT: It looks like you need a view model in mvc or a modification to your post:

public class CompanyViewModel {
      public Company company { get; set; }
}

Or use data: JSON.stringify(customer) instead of data: JSON.stringify({ company: customer })


Here is a working example from a website we are developing. It uses Riot.js instead of angular, but the concepts will be similar.

See also http://www.abeautifulsite.net/postjson-for-jquery/

    $.getJSON(self.baseUrl + "/SaveApplicant", $('form.#applicant').serialize(), function (response) {
        if (response.errorMessage) {
            RiotControl.trigger('error_message', response.errorMessage);
            return;
        } else {
            self.packageQuote.applicant = response;
        }
        RiotControl.trigger("continue","applicant");
    });

Or using post, per the link above

    $.post(self.baseUrl + "/SaveApplicant", $('form.#applicant').serialize(), function (response) {
        if (response.errorMessage) {
            RiotControl.trigger('error_message', response.errorMessage);
            return;
        } else {
            self.packageQuote.census = response;
        }
        RiotControl.trigger("continue","applicant");
    },'json');

There is a bit more involved on the MVC side of things, to send back a json response with lower case property name prefixes:

    public ActionResult SaveApplicant(Applicant model)
    {
        if (ModelState.IsValid)
        {
            var applicant = DbContext.Applicants.FirstOrDefault(row => row.Id == model.Id);
            if (applicant == null) {
                DbContext.Applicants.Add(model);
            } else {
                applicant.Clone(model); // implement as needed or use entity state modified.
            }

            DbContext.SaveChanges();

            return FormattedJsonResult(applicant);
        }
        return ModelErrors();
    }

    public ActionResult FormattedJsonResult(object model)
    {
        var camelCaseFormatter = new JsonSerializerSettings();
        camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
        var result = JsonConvert.SerializeObject(model, camelCaseFormatter);
        return Content(result, "application/json");
    }

    public ActionResult ModelErrors()
    {
        return FormattedJsonResult(
            new
            {
                errorMessage =
                    String.Join("\n",
                        ModelState.Values.SelectMany(value => value.Errors).Select(error => error.ErrorMessage))
            });
        return View();
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.