简体   繁体   English

如何将自定义字段添加到Json结果 - ASP.NET MVC

[英]How to Add Custom Fields to a Json Result - ASP.NET MVC

I am developing an admin page that able to edit registered users info. 我正在开发一个能够编辑注册用户信息的管理页面。 When I select a user from a dropdownlist, the users current info is filling to edit fields. 当我从下拉列表中选择用户时,用户当前信息将填充到编辑字段。 I made it with Javascript and Json. 我用Javascript和Json制作了它。

This is my JS code so far: 到目前为止这是我的JS代码:

$(document).ready(function () {

        $("#UserId").change(function () {

            if ($(this).val() != "" && $(this).val() != undefined && $(this).val() != null) {
                $.ajax({
                    type: "POST",
                    url: "/AdminController/GetUserData",
                    cache: false,
                    data: { userid: $(this).val() },
                    success: function (result) {                         
                        $("#EMailAdress").val(result.EMailAdress)
                        $("#UserName").val(result.UserName)
                    }

                });
            }

            else {
                $("#UserName").val("");
                $("#EMailAdress").val("");
            }

        });
    });

As you see I am trigering "/AdminController/GetUserData" and I have this code in there: 如你所见,我正在试图“/ AdminController / GetUserData”,我在那里有这个代码:

[HttpPost]
    public JsonResult GetUserData()
    {
        int userid = Convert.ToInt32(Request.Form["userid"]);
        MyContext _db = new MyContext();
        var userObj = _db.Users.SingleOrDefault(p => p.UserId == userid);
        return Json(userObj);
    }

Now I have to display the selected user's current role in same page. 现在我必须在同一页面中显示所选用户的当前角色。 I can reach that role data in my controller. 我可以在我的控制器中找到该角色数据。 But I can't find a way to add it to my JsonResult. 但我找不到将它添加到我的JsonResult的方法。 I think I can trigger another controller method that gets role data for the user with another JS code but I think it is not a good way to do this. 我想我可以触发另一个控制器方法,用另一个JS代码为用户获取角色数据,但我认为这不是一个好方法。

I am a begginer so if the solution is easy please don't blame me... I hope I made myself clear. 我是一名初学者,所以如果解决方案很简单,请不要责怪我......我希望自己能说清楚。 Any help would be appreciated. 任何帮助,将不胜感激。

You could define a view model: 您可以定义视图模型:

public class MyViewModel
{
    public User User { get; set; }
    public RoleData Role { get; set; }
}

that your controller action will populate: 您的控制器操作将填充:

[HttpPost]
public ActionResult GetUserData(int userId)
{
    MyContext _db = new MyContext();
    var userObj = _db.Users.SingleOrDefault(p => p.UserId == userId);
    var roleData = .....

    var model = new MyViewModel();
    model.User = userObj;
    model.Role = roleData;
    return Json(model);
}

Notice how the controller action takes the userId as parameter to avoid you from writing plumbing code of parsing it from the request. 请注意控制器操作如何将userId作为参数,以避免编写从请求中解析它的管道代码。 That's already handled by the default model binder. 这已经由默认的模型绑定器处理。

And inside your AJAX success callback you could access the 2 properties of the view model that we defined ( User and Role respectively): 在AJAX成功回调中,您可以访问我们定义的视图模型的2个属性(分别是UserRole ):

success: function (result) {                         
    $("#EMailAdress").val(result.User.EMailAdress);
    $("#UserName").val(result.User.UserName);

    var roleData = result.Role;
    // do something here with the role data
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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