如何将模型中存储的名称和值收集到字典中,并最终将这些单独的变量合并为一个 C# MVC

本文关键字:合并 变量 单独 MVC 一个 存储 模型 字典 | 更新日期: 2023-09-27 18:31:44

我的问题从这个链接继续 如何将模型中存储的名称和值收集到 C# MVC 中的列表中 我的模型是这样的

public class UserModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}

我收集了两个不同的值,它们在此模型中绑定为旧值和新值,我可以将其作为参数发送到我的函数。我想收集这个模型的这些属性的名称,作为一个变量中的 Int、Name、Age、Address,然后使用字典数据结构在两个不同的变量中收集它对应的旧值和新值,以便最后我可以将这三个不同的变量合并为一个并将它们转换为 json 以将它们正确加载到我的网格中。我想以这种方式在网格中显示我的数据。

列旧值新值


姓名 约翰·

约翰1


地址 ADF adfret


10岁

11岁

我已经在列表中完成了此操作。但是由于我无法将三个单独的变量合并到列表中的不同变量中,因此我想使用字典数据结构来执行此操作。请帮忙。

如何将模型中存储的名称和值收集到字典中,并最终将这些单独的变量合并为一个 C# MVC

使用字典似乎是不必要的,我不确定这将如何解决您的问题。我建议您创建一个包含要在视图中显示的 3 个属性的类

public class PropertiesVM
{
    public string Name { get; set; }
    public object OldValue { get; set; }
    public object NewValue { get; set; }
}

并在控制器中

public JsonResult GetProperties()
{
  UserModel old = //
  UserModel new = //
  List<PropertiesVM> model = new List<PropertiesVM>();
  foreach (PropertyInfo propertyInfo in typeof(UserModel).GetProperties())
  {
    PropertiesVM prop = new PropertiesVM();
    prop.Name = propertyInfo.Name;
    prop.OldValue = propertyInfo.GetValue(old, null);
    prop.NewValue = propertyInfo.GetValue(new, null);
    propertyNameList.Add(prop);
  }
  return Json(model, JsonRequestBehavior.AllowGet);
}

在 Ajax 成功回调中,类似

$.each(data, function(index, item) {
  var row = $('<tr></tr>');
  row.append($('<td></td>').text(item.Name));
  row.append($('<td></td>').text(item.OldValue));
  row.append($('<td></td>').text(item.NewValue));
  $('table').append(row);
});