如果可能,Json返回代码以简化

时间:2010-12-27 05:19:11

标签: jquery asp.net-mvc-3

你能简化这段代码吗?有什么我们可以做的,使它更简单。我不确定,但对我来说看起来很难看。

 [HttpPost]
        public JsonResult UserDetailById(int userId, string username)
        {
            IQueryable<Company> repository = companyRepository.GetGridCompanies();
            Employee emp = companyRepository.GetEmployee(userId);

            //Drop down fill
            var a = (from c in repository
                         .OrderBy(c => c.companyName)
                         select new 
                        {
                            Id = c.companyID,
                            Name = c.companyName

                        }).ToArray();

            var data = new 
            {
                 Id = emp.companyID.ToString(),
                               Name = emp.employeeFirstname + " " + emp.employeeLastname,
                               Fn = emp.employeeFirstname,
                               Ln = emp.employeeLastname,
                               Dept = emp.employeeDepartment,
                               Sup = emp.employeeSup.ToString(),
                               HireDate = String.Format("{0:MM/dd/yyyy}", emp.employeeHiredate),

                           CompVm = a
            };


            return Json(data);
        }

2 个答案:

答案 0 :(得分:1)

这就是我制作jQuery ajax和webmethods的方法:

WEBMETHOD:

[WebMethod]
public object populatePgSubCategory(string catId)
{
    StoreDataContext db = new StoreDataContext();

    var a = from n in db.SubCategories
            where n.CategoryID == int.Parse(catId)
            orderby n.SubCategoryName
            select new
            {
                x = n.SubCategoryName,
                y= n.SubCategoryID
            };
        return a;   
}

jQuery ajax:

$.ajax({
            type: "POST",
            url: "/WebService_VehicleDisplay.asmx/populatePgSubCategory",
            data: "{catId:"+"'"+n+"'"+"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var response = msg.d;
                $("#ddlSubCat").empty();
                $.each(response, function (key,val) {
                    $('#ddlSubCat').append(new Option(val.x, val.y));
                });
            },
            failure: function (msg) {
                alert('failure');
            }
        });

答案 1 :(得分:0)

使用json-serializer可以简化构建json数据的第二部分。我使用Json.Net。此序列化程序自动为类读取和写入JSON。

我在您尝试简化的代码中并没有完全了解您正在做的事情,但是当您使用data = JsonConvert.SerializeObject(repository)替换代码时,您将朝着正确的方向迈出一步,我想