简体   繁体   中英

Passing complex object from Angularjs controller to MVC controller is not working

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

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM