如何将字符串转换为MVC控制器中的对象/模型引用/地址?

时间:2016-07-27 08:30:55

标签: c# asp.net asp.net-mvc asp.net-mvc-4

如果我存储了一个字符串,我该如何将该字符串用作对象引用的一部分?

例如,如果我将字段名称存储为字符串,那么当我在表格中引用该字段时,如何使用该字符串:

string thisismystring = fieldname

if (tablename.(this is where i want to use my string as a reference to the appropriate field) > 1)
{
    Do something here

}

由于

1 个答案:

答案 0 :(得分:2)

如果您确实认为需要,可以通过调用模型类型GetProperty来使用反射,然后在返回的PropertyInfo上调用GetValueGetValue采用您的模型类型的实例。

实现返回值是一个对象。要比较它,您可能需要转换或转换它,但这取决于您的逻辑。

// if this is your model ...
public class MyModel 
{
    public string FieldName {get;set;}
}

// this is what your Controler method would look like 
public ActionResult Check(string fieldname, string fieldValue)
{
   var tablename = new MyModel{ FieldName = "check"};
   var prop = typeof(MyModel).GetProperty(fieldname); 
   var value = prop.GetValue(tablename);

   // do notice value is here an Object, so you might want to Convert or Cast if needed
   if (value == fieldValue) 
   {
      "equal".Dump();
   }
   return View(tablename);
}

// and this is how your Controller method gets called
Check("FieldName","check");

请注意,反射会降低性能。