Today, I want to show you how to delete multiple Items in ASP.NET with JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. Now, open your project and write the following code:

View
<table class="table"> 
@foreach (var role in Model) { 
<tr> 
    <td> 
        <input id="responsable1" name="checkResp" value="@role.id" type="checkbox" /> 
        <strong>@role.Name</strong> 
    </td> 
</tr> 

</table> 
<input id="DeleteBtn" type="button" value="Delete Selected" /> 
<script> 
$("#DeleteBtn").on("click", function() { 
    var boxData = []; 
    $("input[name='checkResp']:checked").each(function() { 
        boxData.push($(this).val()); 
    }); 
    $.ajax({ 
        url: '/Roles/DeleteMultiple', 
        data: { 
            RoleId: boxData.join(",") 
        }, 
        cache: false, 
        type: "POST", 
        timeout: 10000, 
        dataType: "json", 
        success: function(result) { 
            window.location.reload(); 
        } 
    }); 
}); 
</script> 


Controller
[HttpPost] 
public JsonResult DeleteMultiple(string RoleId) { 
ApplicationDbContext db = new ApplicationDbContext(); 
var RoleIds = RoleId.Split(','); 
foreach(var id in RoleIds) { 
    int idConverted = Convert.ToInt32(id); 
    Roles roleid = db.Roles.Find(idConverted); 
    db.Roles.Remove(roleid); 

context.SaveChanges(); 
var message = "Selected roles have been deleted"; 
return Json(message); 


DeleteMultiple - Action Name
Roles - Controller Name

 

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.