asp.net mvc - Remove / Delete a dynamically created partial view mvc -


i trying add remove/delete dynamically created partial view. add script.

    $("#btnadd").on('click', function () {     $.ajax({         async: false,         url: '/employees/add'     }).success(function (partialview) {         $('#addschedule').append("<tbody>" + partialview + "</tbody>");           }); }); 

this add controller

public actionresult add()     {         var schedviewmodel = new facultyschedviewmodel();         return partialview("~/views/employees/_dynamicview.cshtml", schedviewmodel);     } 

this partial view _dynamicview.cshtml

@using(html.begincollectionitem("new")){     <td>         @html.actionlink("delete", "deletethis", "mycontroller", null)     </td>     <td>         @html.editorfor(model => @model.schedule, new { htmlattributes = new { @class = "form-control" } })     </td> } 

what can't figure out

  1. how id generated beginitemcollection
  2. use id in remove script
  3. action on controller

edit 1. how connect button or link removing row

added view on the main of partial view

 @for (int = 0; < @model.new.count(); i++)                 {                                   @html.editorfor(model => @model.new[i])                  } 

the beginitemcollection add guid indexer controls name , id attributes. has no relevance @ identifying item delete. need add include value of property identifies facultyschedviewmodel object. assuming int id, change partial include button , add id data- attribute

@using(html.begincollectionitem("new")) {   <tr>     <td><button type="button" class="delete" data-id="@model.id">delete</button></td>     <td>@html.editorfor(model => @model.schedule, new { htmlattributes = new { @class = "form-control" } })</td>   </tr> } 

then script

var url = '@url.action("delete")'; // assumes in same controller $('.delete').click(function() {   var id = $(this).data('id');   var row = $(this).closest('tr');   if (id) { // or if(id == 0) depending if property nullable     row.remove(); // item never existed no need call server     return;   }   $.post(url, { id: id }, function(response) {     if(response) {       row.remove(); // ok, remove row     } else {       // oops - display , error message?     }   }); }); 

and controller

[httppost] public jsonresult delete(int id) {   // delete item in database   return json(true); // or if there error, return json(null); indicate failure } 

side note:

  1. $('#addschedule').append("<tbody>" + partialview + "</tbody>"); adding new tbody element each item. instead main view should include tbody element , give id $('#addschedule').append(partialview); or use $('#addschedule tbody')append(partialview);
  2. does model posting have property named new (as indicate in beginitemcollection method)?

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -