I recently learned about asp.net mvc. Let's talk about "delete.
To delete a page that displays a data list, http supports get and post requests on the web,
If you want to display data on the same page and perform the delete operation, you can call ajax to support more request methods (put, delete, head, etc ).
First, display the data list:
Controller Code: Code
Public ActionResult Index (int? PageIndex)
{
PageList <Movie> list = new PageList <Movie> ();
IQueryable <Movie> query = from m in movie. Movie select m;
Int pageSize = 10;
Int currentPage = pageIndex ?? 1;
Int count = 0;
Count = query. Count ();
List. RowCount = count;
List. PageSize = pageSize;
CurrentPage = currentPage <1? 1: currentPage> list. TotalPages? List. TotalPages: currentPage;
List. CurrentPage = currentPage;
If (count <1)
{
List. List = new List <Movie> ();
}
Else
{
List. List = query. Skip <Movie> (currentPage-1) * pageSize). Take (pageSize );
}
Return View (list );
}
Note: The PageList <> class is a custom paging class.
Show data: Code
<Table id = "data">
<Tr>
<Th>
Id
</Th>
<Th>
MovieName
</Th>
<Th>
CategoryName
</Th>
<Th> Details </th>
<Th> Update </th>
<Th> Delete </th>
</Tr>
<% Foreach (var item in (Model as Common. PageList. PageList <MvcDemo. Models. Movie>). List) {%>
<Tr>
<Td>
<% = Html. Encode (item. Id) %>
</Td>
<Td>
<% = Html. Encode (item. MovieName) %>
</Td>
<Td>
<% = Html. Encode (item. CategoryName) %>
</Td>
<Td>
<% = Html. ActionLink ("Details", "Details", new {id = item. Id}) %>
</Td>
<Td>
<% = Html. ActionLink ("Update", "Edit", new {id = item. Id}) %>
</Td>
<Td> <a href = "javascript: void (0);" onclick = "del (this, <% = item. id %>); "> Delete </a> </td>
</Tr>
<% }%>
</Table>
The del method is used for deletion. The Code is as follows: Code
Function del (obj, mId)
{
If (confirm ("are you sure you want to delete? "))
{
$. Ajax (
{
Url: "/Movie/Delete/" + mId,
Type: "DELETE ",
Success: function ()
{
$ (Obj. parentNode. rows [obj. parentNode. parentNode. rowIndex]). remove ();
Alert ("deleted successfully! ");
// Window. location. reload ();
},
Error: function (XMLHttpRequest, textStatus, errorThrown)
{
Alert ("deletion failed! \ N information: "+ errorThrown +", "+ textStatus +" \ n ");
}
}
);
}
}
The ajax function of jquery is referenced here. The Request Method for deletion is DELETE, which is specified by the type: "DELETE" above.
The deletion Code on the server side is as follows, which is relatively simple: Code
[AcceptVerbs (HttpVerbs. Delete)]
Public void Delete (int id)
{
Try
{
Movie mov = (from m in movie. Movie where m. Id = id select m). First ();
Movie. Movie. DeleteOnSubmit (mov );
Movie. SubmitChanges ();
}
Catch
{}
}