I have a view where I add some elements to a table from Database; let’s call the table Students. On the view I also have the option to assign to the student I am adding to the table some books . I have done this with Ajax.
Demo:
Name of Student: ...
Books : <here is a drop down> ( from database) < here is a button> (add button)
<ul>
When I click the button here I append some books. I also retain on Session the id of every book ( in a list and when I click submit I send that list to the server )
</ul>
[Submit button]
The problem is that I want to add a delete buton too like this :
Name of Student: ...
Books : <here is a drop down> < here is a button>
<ul>
Book1 delete
Book2 delete
</ul>
[Submit button]
And when I click the delete button to remove that element from the list and from the Session.
Here is my code:
-
Script from the View
$(function () { $("#add").click(function () { //items.push($("#category").val()); $.ajax({ url: '@Url.Action("AddCategory")', type: "POST", dataType: "JSON", data: { id: $("#categoryId option:selected").val() }, beforeSend: function () { }, success: function (data) { $("#toFill").append("<li>" + $("#categoryId option:selected").text() + " " + "<span style='cursor:pointer;' id='a'>" + "[X]" + "</span>" + " " + "</li>"); }, error: function () { alert("error") } }) $("#toFill #a").click(function () { $.ajax({ url: '@Url.Action("DeleteCat")', type: "POST", dataType: "JSON", data: { id: $("#categoryId option:selected").val() }, beforeSend: function () { }, succes: function (data) { // $("li").remove(); alert("lala"); return false; }, error: function () { alert("error at delete") } }) }); }) -
AddCategoryandDeleteCatfrom Controller:public ActionResult AddCategory(int id) { Session.Category.Add(id); return Json(id, JsonRequestBehavior.AllowGet); } public ActionResult DeleteCat(int id) { Session.Category.Remove(id); return Json(id, JsonRequestBehavior.AllowGet); }
It will be more logical and easier to follow, use and program if you have one delete button acting on the drop down directly – i.e. select an item in drop down and click delete to delete the selected item.