lundi 7 mars 2016

How can I create a generic controller to update a specific data field

I'm currently writting a system which allows customers to update their data. Currently each item of data e.g. email address, phone number etc... is going to be loaded and displayed with it's own controller. I'm having to a use a controller per line of data, as the CMS I'm using dictates the system to be designed that way.

So, effectivly, I'll have a controller to load and save the customer's email address, another to load and the customer's mobile number etc...

Rather than write a number of controllers which handle a specific data field, I was trying to figure out a way to make one controller generic, and be able to load/save the relevant data.

All of the data fields will be contained in an object in session, and a provider is used to retrive the object from session. Saving however, is just a call to the database (I can ignore the session object).

One of the things I have to think about is the customer (my client - not the one using the website), may wish the page to load/save another field of data, if another one gets added to the system ast some point (e.g. secondary phone number), so I have to think abouyt maintainability.

My initial though was to use reflection, so I would have something like

private string field {get;}

UpdateDataController(string field)  {
    this.field = field;
}

public loaddata()
{
   CustomerData data = provider.getsessionobject();
   string value = data.GetType().GetProperty(field).GetValue(data, null);
   return View("viewname", new CustomerViewModel(value));
}

public savedata(string newvalue)
{
     savedataprovider.GetType().GetMethod("update" + field).Invoke(savedataprovider, new object[] { newvalue });
}

I dont like this as not only does it look like a horrible hacky solution, but also I imagine there will be a performance hit on using reflection.

Is there a better way to do this?





Aucun commentaire:

Enregistrer un commentaire