将表单数据序列化为特定的JSON格式

时间:2016-05-26 18:58:34

标签: javascript c# angularjs json asp.net-mvc

我的表格看起来像这样:

<form id="myForm" ng-submit="submitForm()">
    <select name="ItemName" ng-controller="ItemController">
        <option value="" selected disabled>Select</option>
        <option ng-repeat="item in items track by $index" value="{{item.Id}}">{{item.Name}}</option>
    </select>
    <input type="text" name="Description" />

    <button type="submit">Submit</button>
</form>

我的AngularJS FormController然后执行以下操作:

form.controller.js

app.controller('FormController', function($scope, $http) {

$scope.submitForm = function () {
    $http({
            method: 'POST',
            url: '/Path/To/MVC/Action',
            data: { json: JSON.stringify($('#myForm').serializeArray()) }
        })
        .success(function(data) {
            console.log('success');
        })
        .error(function(error) {
            console.log('failure);
        });
    };
});

我希望我的MVC控制器接收如下所示的json字符串:

{
    "Name": "some item name",
    "Description": "some item description"
}

使用serialize(),我得到了类似的东西:

Name=some%20item%20name&Description=some%20item%20description

...并且使用serializeArray(),我得到了类似的东西:

[{
    name: "Name",
    value: "some item name"
},
{
    name: "Description",
    value: "some item description"
}]

如何以我正在寻找的格式获取JSON字符串?

2 个答案:

答案 0 :(得分:0)

这是你在找什么?我对某些项目有点不清楚等等:

https://plnkr.co/edit/IFHNtxS226Hq0cCMJYi1?p=preview

  $scope.submitForm = function(formData){

    console.warn(formData);

    $http({
            method: 'POST',
            url: '/Path/To/MVC/Action',
            data: { json: formData }
        })
        .success(function(data) {
            console.log('success');
        })
      .error(function(error) {
            console.log('failure');
        })

  }
});

答案 1 :(得分:0)

您使用的是WebAPI吗?

您可以替换此选项:

<select id="selectId" type="text" ng-required="true" name="nameOfSelect" class="form-control" ng-model="yourModel.ObjectForThisSelect" placeholder="String Inside you Select"
      ng-options="info.Value as info.Text for info in items>
</select>

然后你应该回复&#34; yourModel&#34;对象,这种方式回发时Angular将仅序列化所选的选项值。

此外,如果您使用的是WebApi,您可以检查您的WebApiConfig类,Register(HttpConfiguration config)方法,即您正在格式化所需格式的Json字符串:即

 var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
            jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();