如何从字典中传递表单值到c#中的对象
本文关键字:String 对象 字典 表单 | 更新日期: 2023-09-27 18:15:01
我从字典中的表单获得值。键等于字段上的页面和值是什么用户提供。是否有一个更好的方法来传递值的对象如下:我是新的,所以会感谢你的帮助。谢谢你的帮助
我使用以下调用获得这些值:
public async void PostFormData()
现在我正在尝试将值从字典传递到一个对象,如下所示。下面的方法是非常基本的,我希望使它更动态。
public static void ConverttoObject()
{
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("Name", "Daniel");
test.Add("LastName", "Wong");
test.Add("Zip", "60004");
test.Add("City", "New York");
var abc = new FormInfo();
foreach (var key in test.Keys)
{
foreach (var val in test.Values)
{
if (key.Equals("Name"))
abc.Name = val;
else if (key.Equals("LastName"))
abc.City = val;
else if (key.Equals("Zip"))
abc.Zip = val;
else if (key.Equals("City"))
abc.City = val;
}
}
}
}
public class FormInfo
{
public string Name { get; set; }
public string LastName { get; set; }
public string Zip { get; set; }
public string City { get; set; }
}
您可以创建自己的扩展方法来将字典转换为如下的对象:
public static class IDictionaryExtensions
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
T someObject = new T();
Type someObjectType = someObject.GetType();
foreach (KeyValuePair<string, object> item in source)
{
someObjectType.GetProperty(item.Key).SetValue(someObject, item.Value, null);
}
return someObject;
}
}
解决方案。
你能不能:
abc.Name = test["Name"];
abc.LastName = test["LastName"];
abc.Zip = test["Zip"];
abc.City = test["City"];