将复杂对象从Angularjs控制器传递到MVC控制器不起作用

时间:2015-10-15 18:38:10

标签: javascript html angularjs asp.net-mvc asp.net-mvc-4

在Angular控制器的Ajax调用中,我将一个复杂的对象作为数据传递。在MVC上,控制器对象具有所有空值。 我有下面给出的MVC视图,它将是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>

使用AngularJS,我将加载注册客户视图,注册客户视图标记如下。我已使用ng-click指令将客户功能注册到按钮。

<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>

我有角度控制器,它具有名为registerCustomer()的功能,将在点击注册客户时调用。我在该函数中有一个ajax调用,如下所示。

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

在MVC上,我有一个名为Company的模型,如下所示。

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

我的MVC控制器看起来像

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

总是我在MVC控制器上有空对象,如果我遗漏任何东西,请帮助我。提前致谢

1 个答案:

答案 0 :(得分:0)

编辑:看起来您需要mvc中的视图模型或修改帖子:

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

或使用data: JSON.stringify(customer)代替data: JSON.stringify({ company: customer })

以下是我们正在开发的网站的工作示例。它使用Riot.js代替角度,但概念将类似。

另见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");
    });

或使用帖子,按照上面的链接

    $.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');

在MVC方面还有一些涉及的事情,发回一个带有小写属性名称前缀的json响应:

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