c# - Cannot add object to context.DbSet. SaveChanges not working -
i have method in controller:
public actionresult reserve(int id) { viewbag.staffid = new selectlist(context.staffs, "staffid", "fname"); viewbag.roomid = id; return view(); } the corresponding view:
@model _00002165.models.reservation @{ viewbag.title = "reserve"; } <h2>reserve</h2> @using (html.beginform()) { @html.validationsummary(true) <div class="editor-label"> <label>room number</label> </div> <div class="editor-field"> <input type="text" value="@viewbag.roomid" readonly name="roomid"/> </div> <div class="editor-label"> @html.labelfor(model => model.fromdate) </div> <div class="editor-field"> @html.textboxfor(model => model.fromdate) @html.validationmessagefor(model => model.fromdate) </div> <div class="editor-label"> @html.labelfor(model => model.todate) </div> <div class="editor-field"> @html.textboxfor(model => model.todate) @html.validationmessagefor(model => model.todate) </div> <div class="editor-label"> <label>staff:</label> </div> <div class="editor-field"> @html.dropdownlist("staffid", "select staff") @html.validationmessagefor(model => model.staffid) </div> <button type="submit">reserve</button> } and want save data these inputs these post method:
[httppost] public actionresult reserve(reservation res) { if (modelstate.isvalid) { var customer = context.customers.first(x => x.username == user.identity.name); res.customerid = customer.customerid; context.reservation.add(res); context.entry(res).state = entitystate.modified; context.savechanges(); return redirecttoaction("index"); } } this giving me following error:
store update, insert, or delete statement affected unexpected number of rows (0). people suggest add @html.hiddenfor(model => model.reservationid) view.
but model.reservationid empty.
how can fix this? please help
you shouldn't passing data transfer objects to/from views. create view model tomodel method return dto want. adding context, don't need change state.
use this
context.reservation.add(res); context.savechanges(); removing
context.entry(res).state = entitystate.modified; if trying update, pull record database, make changes , call savechanges
Comments
Post a Comment