Wednesday, October 10, 2012

how to delete row from datalist using ajax in asp.net mvc2

Let's design the form and load data, so it look like a datalist, in mvc2 you don't need to use any datalist control for that, this is more likely how we used to write classic asp in earlier days. here at the end of each row i have added a delete link, and we see how on click on that link the respective row gets deleted.

< div id="dvClients">

< % using (Html.BeginForm("ShowClient", "Client", FormMethod.Get))
{%>
< table>
< % foreach (var item in Model.Clients)
{ %>
< tr>
< td>
< %: Html.ActionLink("Edit", "EditClient", "Client", new { ContactId = item.ContactId }, new { })%>
< %: Html.ActionLink("Details", "Details", new { ContactId = item.ContactId }, new { })%>
< /td>
< td>
< %: item.ContactId%>
< /td>
< td>
< %: item.OrgName%>
< /td>
< td>
< %: item.Address%>
< /td>
< td>
< a href="javascript:DeleteClient('< %: item.ContactId%>')">Delete< /a>
< /td>
< /tr>
< % } %>
< /table>
< %} %>
< /div>  

Now we write some javascript function to make ajax call. lets see how the simple javascript will look like!!

< script language="javascript" type="text/javascript">
function DeleteClient(clientId) {
var isConfrm = window.confirm("Are you sure you want to delete?");
if (isConfrm) {
DeleteCall(clientId);
}
}

function DeleteCall(cId) {
var data = "clientId=" + cId;
$.ajax({
url: "DeleteClient",
data: data,
type: "POST",
dataType: "json",
success: function (data, status, xhr) {
alert("the row has been deleted successfully.");
},
error: function (xhr, status, err) {
alert(err + xhr + status);
}
});
}
< /script>

Now we write a controller to delete the data from database, here in this example i have set myclass = clientid, you can send the complete object to your javascript, so the script function can create appropriate message for end user to read the operation result.

[HandleError]

public class ClientController : Controller
{
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteClient(string clientId)
{
ClientService.DeleteClient(Convert.ToInt64(clientId));
return Json(new { success = true, value = "done", newClass = clientId });
}
}

No comments:

ETG Consultancy

Web Designing Development Analysis & Promotion
Asp.Net 2.0 SQL WWF WCF SEO Marketing Ajax JQuery NHibernate MVC