im new .net.. start mvc c#..
i have problem here.. im trying update logo after insert it. if dont select image file, logo location (im store location part in db) come "null"..
here controller:
public actionresult edit(payroll_company payroll_company) { if (modelstate.isvalid) { httppostedfilebase txtuploadfile = request.files["txtuploadfile"]; if (txtuploadfile != null && txtuploadfile.contentlength > 0) { string logo = txtuploadfile.filename; payroll_company.comp_logo = logo; var path = path.combine(server.mappath("~/logo/"), logo); txtuploadfile.saveas(path); } else { //payroll_company comp = db.payroll_company.find(payroll_company.comp_id); //payroll_company.comp_logo = comp.comp_logo; } db.entry(payroll_company).state = entitystate.modified; db.savechanges(); return redirecttoaction("index"); } return view(payroll_company); } here view:
<div class="form-group"> <label class="control-label col-md-2">logo</label> <div class="col-md-10"> <input type="file" name="txtuploadfile" id="txtuploadfile" class="form-control"> </div> </div> how can edit company information if dont select image file , remain old image?? hope out there can me solve this..
thanks in advance
var logopath = directory.getfiles(server.mappath("~/logo/")).orderbydescending(f => file.getcreationtime(f)).firstordefault(); if (!string.isnullorwhitespace(logopath)) { payroll_company.comp_logo = path.getfilename(logopath); } add code else part,because need last image file,it means created laster other image files.otherwise,you need read db first,yes,you have it.
after answer,it seems payroll_company 1 property!,so why save it? need skip the save code,and leave the return code when there no image uploaded
your exception means object attched context,so must detach first,then attach again
var _dc = (iobjectcontextadapter)db; var _oc = _dc.objectcontext; var key;// = payroll_company.key; objectstateentry ose; if (_oc.objectstatemanager.trygetobjectstateentry(key, out ose)) { var _entity = (payroll_company)ose.entity; db.entry(_entity).state = entitystate.detached; } db.payroll_company.attach(payroll_company); db.entry(payroll_company).state = entitystate.modified;
Comments
Post a Comment