Reputation: 18072
I have a list view:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="NoteId" DeleteMethod="ListView1_DeleteItem" ItemType="NotesPractice.Note" SelectMethod="ListView1_GetData"
<ItemTemplate>
...
<asp:Button ID="btnDelete" CausesValidation="false" CommandName="Delete" runat="server" Text="Delete" />
...
</ItemTemplate>
</asp:ListView>
The DeleteMethod ListView1_DeleteItem
:
public void ListView1_DeleteItem(int id)
{
System.Diagnostics.Debug.WriteLine("The id of button is: " + id);
using (var db = new NotesContext())
{
var note = (from n in db.Notes
where n.NoteId == id
select n).Single();
db.Notes.Remove(note);
db.SaveChanges();
}
If I look in browser console I see this exception rising:
Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: A null value for parameter 'id' of non-nullable type 'System.Int32' for method 'Void ListView1_DeleteItem(Int32)' in 'NotesPractice._Default'. An optional parameter must be a reference type or a nullable type.
This suggests that the NoteId
value (which is specified in the DataKeyNames) is not reaching the delete method, thus it's throwing the exception. Why isn't any data reaching the method?
I also tried explicitly specifying the DataKeyNames with no luck:
DataKeyNames="NotesPractice.Note.NoteId"
Here is a copy of my database:
Upvotes: 2
Views: 382
Reputation: 21795
Change your Delete method like this:-
public void ListView1_DeleteItem(int NoteId)
Model Binding feature requires this as per the design.
The id parameter name should match the DataKeyNames value set on the control
Check Dan Wahlin's blog for more details.
Upvotes: 3