when creating a new View and selecting Edit template, the template will create a textbox for the primary key which is not editable.
<%=Html.TextBox("CompanyID", Model.CompanyID)%>
So, deleting the control from view, will cause the problem: the collection which is post to controller has the CompanyID=0 , so no edit will be done. But if I put back that line of code to view, the CompanyID in posted collection has the proper value. I am doing much like this tutorial: http://www.asp.net/learn/mvc/tutorial-21-vb.aspx , and there ( gray box above "Listing 6 – Controllers\HomeController.vb (Edit methods)" section ) it is saying you can delete the control, but its not working.. any advice?
Updated
Ok, for more explain, here goes 2 problems:
problem 1 in this code:
<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal movieToEdit As Movie) As ActionResult
if you remove the MovieID textbox from view the movieid in movietoedit collection is always zero, so the tutortial from the asp.net website wont work! if I want to delete the movieID from view, I have to pass the ID to my controller like this:
<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal ID as integer,ByVal movieToEdit As Movie) As ActionResult
now I can query Model using this ID.. thats no problem, but it takes me some times to figuring out, as I was doing step by step from the website !
Problem 2 So, How to do Edit without using the movieID in view, even in hidden textbox?
I am using this as my controller: ( using Enity framework )
<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal id As Integer, ByVal collection As Company) As ActionResult
If Not ModelState.IsValid Then
Return View()
End If
Try
Dim c = _db.CompanySet.FirstOrDefault(Function(m) m.CompanyID = id)
If c Is Nothing Then
Return RedirectToAction("index")
End If
_db.ApplyPropertyChanges(c.EntityKey.EntitySetName, collection)
_db.SaveChanges()
Return RedirectToAction("Index")
Catch ex As Exception
Throw ex
End Try
End Function
And if I remove CompanyID from my view ( textbox or hidden field ) it will give me this error from c.EntityKey.EntitySetName:
The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'Companies.Company'.
and if I add something like
<%= Html.TextBox("CompanyName", Model.CompanyName) %>
it will work fine .. I am confused!
note: I checked the code more than 10 times, and I wonder if there is anything I am doing wrong or the tutorial is wrong ..