从json中删除xml标记

时间:2015-06-22 13:35:05

标签: c# asp.net angularjs

web方法以此格式返回json字符串。

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">
[{"PKAdminUserId":1,"Username":"one","Password":"onep"},
{"PKAdminUserId":2,"Username":"two","Password":"twop"}]
</string>

由于这个原因,数据没有绑定到表。如果我将数据硬编码到$scope.Users而没有xml/string标记,则可以正常使用。 如何在没有xml<string>标记的情况下仅从webmethod获取json数据。

的.aspx:

<table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Username</th>
                    <th>Password</th>
                </tr>                
            </thead>
            <tbody>
                <tr data-ng-repeat="User in Users track by $index">
                    <td>{{User.PKAdminUserId}}</td>
                    <td>{{User.Username}}</td>
                    <td>{{User.Password}}</td>
                </tr>
            </tbody>
        </table>

的.asmx:

[WebMethod]        
        public string GetUsers()
        {
            AdminUser obj;
            List<AdminUser> lstAdminUsers = new List<AdminUser>();
            obj = new AdminUser();
            obj.PKAdminUserId = 1;
            obj.Username = "one";
            obj.Password = "onep";
            lstAdminUsers.Add(obj);
            var json = new JavaScriptSerializer().Serialize(lstAdminUsers);            
            return json;
}

userCtrl.js:

$scope.Users = [];
$scope.GetUsers = function () {
        var promise = Factory.GetUsers();
        promise.then(function (success) {
            console.log(success.data);
            $scope.Users = success.data;
        },
        function (error) {
            console.log("ERR : " + error);
        })
    }

解决方案:

从@Sain Pradeep的链接找到我的解决方案。以下是我的Web方法现在的样子:

[WebMethod]
public void AddUsers()
{
AdminUser obj;
List<AdminUser> lstAdminUsers = new List<AdminUser>();
obj = new AdminUser();
obj.PKAdminUserId = 1;
obj.Username = "one";
obj.Password = "onep";
lstAdminUsers.Add(obj);
JavaScriptSerializer serializer = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HttpContext.Current.Response.Write((serializer.Serialize(
                      serializer.Serialize(lstAdminUsers))));
}

输出

[{"PKAdminUserId":1,"Username":"one","Password":"onep"}]

1 个答案:

答案 0 :(得分:3)

你应该直接将数据作为Json返回,而不是作为Xml(以避免包装)。

尝试更新您的网络方法:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
[WebMethod]        
public List<AdminUser> GetUsers()
{
    AdminUser obj;
    List<AdminUser> lstAdminUsers = new List<AdminUser>();
    obj = new AdminUser();
    obj.PKAdminUserId = 1;
    obj.Username = "one";
    obj.Password = "onep";
    lstAdminUsers.Add(obj);

    obj = new AdminUser();
    obj.PKAdminUserId = 2;
    obj.Username = "two";
    obj.Password = "twop";
    lstAdminUsers.Add(obj);

    return lstAdminUsers;
}