c# - textbox data writes back to database, but textboxfor will not -
i'm picking it's best practice use strongly-typed textboxfor helper method rather simple textbox. i'm that. made switch in project, data stopped getting written database. i'm having trouble figuring out why.
here's model.
public class mastermodel { [key] public int mandatorykey { get; set; } public list<tbladdress> address { get; set; } public list<tblprimarycaregiverdata> primary { get; set; } public list<tblphone> phone { get; set; } public list<tblemail> email { get; set; } public list<tblrelatedcaregiver> related { get; set; } public list<tbltraininghistorymain> traininghistory { get; set; } public list<tblinquiryreferralstatu> inquiryreferral { get; set; } } then controller
public actionresult create(mastermodel mastermodel) { if (modelstate.isvalid) { db.tblprimarycaregiverdatas.add(mastermodel.primary[0]); db.savechanges(); int newcaregiverid = db.tblprimarycaregiverdatas.orderbydescending(p => p.caregiverid) .firstordefault().caregiverid; foreach (var ph in mastermodel.phone) { ph.caregiverid = newcaregiverid; db.tblphones.add(ph); } db.savechanges(); return redirecttoaction("index"); } now, in view (which invokes several partial views, 1 each table in master model), when created fields this:
selectlist phonetypes = viewbag.phonetype; <div> <label class="label-fixed-width">phone:</label> @html.textbox("mastermodel.phone[0].phone", null, new { style = "width: 600px" }) @html.dropdownlist("mastermodel.phone[0].phonetype",phonetypes, null, new { @class = "form-control-inline dropdown", style = "width: 100px" }) ...i able write data database. when switched on textboxfor this:
selectlist phonetypes = viewbag.phonetype; <div> <label class="label-fixed-width">phone:</label> @html.textboxfor(x => x.phone[0].phone, null, new { style = "width: 600px" }) @html.dropdownlistfor(x => x.phone[0].phonetype, phonetypes,"--------", new { @class = "form-control-inline dropdown", style = "width: 100px" }) the phone section of mastermodel empty when post back. can me understand what's going on here?
when post model actionresult , return same view, values model objects contained in modelstate. modelstate contains information valid/invalid fields actual posted values. if want update model value, can this:
foreach (var ph in mastermodel.phone) { modelstate.clear()//added here ph.caregiverid = newcaregiverid; db.tblphones.add(ph); }
Comments
Post a Comment