Rob Rob - 3 months ago 8
ASP.NET (C#) Question

How can I convert a string to use as an object/model reference/address in an MVC controller?

If I have a string stored, how can I use that string as part of an object reference?

For example if I have a field name stored as a string, how can I use that string when I'm referencing that field in a table:

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

}


Thanks

Answer

If you really think it is needed you can use reflection by calling GetProperty on the type of your model and then call GetValue on the PropertyInfo that was returned. GetValue takes an instance of your model type.

Realize the returned value is an object. To compare it you might need to cast or Convert it but that depends on your logic.

// 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");

Be aware that reflection has a performance penalty.