locked
Editing SQL database items and Model Binding attributes? RRS feed

  • Question

  • User281366353 posted

    Problem: I want to update an SQL database record and not create a new database entry.

    The ASP.Net Core MVC application I am working on involves inventory tracking.  Data are stored in an MS SQL server database, by means of Entity FrameworkCore and LocalHost.  That all seems to be working well.  

    Once a PullHdr (pull header) object has been stored I want to enable editing to display and update the order Status.  Users can select a Pull from a <select> element rendered in a Razor View.  The individual Pull is then displayed in another Razor view named PullDisplay.cshtml.  I have enabled the Status property of the PullHdr type with a dropdown list to update the Status property of the order.  Individual PullItems are also displayed on the form/view with the intent of updating the quantities ordered and shipped.  PullDisplay.cshtml receives a PullDisplayViewModel as data source which contains a PullHdr object (PHdr) and a Dictionary<str, str> of Item descriiptions..

    I've not made it past editing PullHdr.Status.  Once a PullHdr object is displayed and the Status changed I call the PullHdrChanged(PullHdr phdr) action method.  Status and other fields are sent to PullHdrChanged method and arrive intact.  However, the PullHdrId, which is the primary key in the SQL database is not carried forward from the PullDisplay View to the PullHdrChanged action method, nor are the individual PullItems from the PullItemList.  PullHdrId is an integer type and is reset to zero. Rather than updating the existing record, a zero value for PullHdrId causes a new PullHdr object to be created, that has the correct Status, but none of the PullItems from the list. 

    I've used typical <label><input>  structures for all the properties except PullHdrId where I use the following:

    <input type="hidden" asp-for="PHdr.PullHdrId" value="@Model.PHdr.PullHdrId" />

    where PHdr is the PullHdr object from the view model.  How do I pass the PullHdrid back to the posting method and tell SQL server to save the updated values and not create a new instance of PullHdr?

    Any constructive comments would be deeply appreciated.

    Saturday, May 22, 2021 4:49 PM

Answers