c# - Circumventing the const requirement of parameters for a custom attribute -
i'm looking ways circumvent restrictions on attribute parameters when creating custom attribute. specifically, have custom displayname attribute goes , retrieves data database , determines display in labelfor helper on view. part of larger prototype, code refinement secondary concern right now. we'll implementing caching , other performance refinements when we're ready start developing actual project. can provide context actual problem, i'm hoping answers general enough apply type of attribute needs this.
the constructor doesn't work besides assigning parameters private properties:
public displaynametranslationattribute(string pagename = "", [callermembername] string fieldname = "") { _pagename = pagename; _fieldname = fieldname; }
all of heavy lifting occurs in displayname override method. reason displayname called every time page loads, opposed constructor called once when page first loaded , never again.
public override string displayname { { string displayname = string.empty; _customerid = 1; //this needs accessed or retrieved somehow, somewhere using (var db = new somedataentities()) { somedata sd = db.somedatas.firstordefault(t => t.pagename == _pagename && t.fieldname == _fieldname); someotherdata od = null; if (sd != null) { od = sd.someotherdatas.firstordefault(c => c.customerid == _customerid); displayname = equals(od, null) ? sd.columnn : od.columnz; } } return displayname.isnullorwhitespace() ? _displayname : displayname; } }
as can see, i'm right hard-coding _customerid 1. need able provide actual value _customerid. know can't pass parameter directly attribute, need discover methods circumvent restriction. there options trick attribute or, more likely, retrieve id somewhere else in memory?
i never imagine display attribute miss-used that. please stop doing that!
if label name taken db, part of domain knowledge , should not treated view logic (which displayname
attribute is).
instead of having these hacks, information viewmodel passed controller view. , controller take data db. simple!
// pseudo-code public actionresult indes(int customerid) { var viewmodel = new viewmodel(); viewmodel.value = dbcontext.customers.firstordefault(c => c.customerid == customerid); viewmodel.displayname = dbcontext.fieldnames.firstordefault(f => f.name == condition); return view(viewmodel); }
edit: second thought, can try create own attribute, separate display attribute, place there field should place there. , implement dataannotationsmodelmetadataprovider giving correct field names labels.
see sample implementation of metadata provider in little app. shamelessly stolen jimmy bogard. implementation not need, shows sample.
Comments
Post a Comment