2017-02-22 14 views
0

Я пытаюсь получить мою кнопку удаления из модального всплывающего окна, чтобы удалить строку из моей локальной базы данных, которая находится в Visual Studio.Удаление строки из DataTable в asp.net

Я не совсем уверен, как это сделать. Я новичок в этом, поэтому, если мне придется добавить некоторые данные. Пожалуйста сообщи мне.

Это контроллер:

using MusicBox.Models; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Mvc; 

namespace MusicBox.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     public ActionResult About() 
     { 
      ViewBag.Message = "Your application description page."; 

      return View(); 
     } 

     public ActionResult Contact() 
     { 
      ViewBag.Message = "Your contact page."; 

      return View(); 
     } 

     //Tab Box 
     //[HttpGet] 
     public ActionResult Box() 
     { 
      return View(); 
     } 


     ////Dobivanje liste unutar gumba 
     [HttpGet] 
     public ActionResult Create() 
     { 
      var viewModel = new MusicViewModel(); 
      var genres = new List<Genre>(); 
      var genreList = new List<SelectListItem>(); 
      using (var db = new ApplicationDbContext()) 
      { 
       genres = db.Genres.ToList(); 
      } 

      foreach (var genre in genres) 
      { 

       genreList.Add(new SelectListItem() { Value = genre.Id.ToString(), Text = genre.Type }); 
      } 

      viewModel.Genres = genreList; 

      return View(viewModel); 
     } 

     [HttpPost] 
     public ActionResult Create(MusicViewModel model) 
     { 
      //Ovo je validation message 
      //if (!ModelState.IsValid) 
      //{ 
      // var viewModel = new MusicViewModel(); 
      // var genres = new List<Genre>(); 
      // var genreList = new List<SelectListItem>(); 
      // using (var db = new ApplicationDbContext()) 
      // { 
      //  genres = db.Genres.ToList(); 
      // } 

      // foreach (var genre in genres) 
      // { 

      //  genreList.Add(new SelectListItem() { Value = genre.Id.ToString(), Text = genre.Type }); 
      // } 

      // viewModel.Genres = genreList; 

      // return View(viewModel); 
      //} 

      var song = new Song 
      { 
       GenreId = model.GenreId, 
       Performer = model.Performer, 
       Title = model.Title, 
       Year = model.Year, 
       YoutubeLink = model.YoutubeLink 
      }; 




      using (ApplicationDbContext db = new ApplicationDbContext()) 
      { 
       try 
       { 
        db.Songs.Add(song); 
        db.SaveChanges(); 
       } 
       catch (Exception e) { } 
      } 



      //ovdje ide dodavanje u bazu 
      return RedirectToAction("List"); 
     } 

     public ActionResult List() 
     { 
      var songs = new List<Song>(); 
      var songList = new List<SongListViewModel>(); 

      try 
      { 
       using (ApplicationDbContext db = new ApplicationDbContext()) 
       { 
        songs = db.Songs.ToList(); 

        foreach (var song in songs) 
        { 
         songList.Add(new SongListViewModel 
         { 
          Performer = song.Performer, 
          Song = song.Title, 
          Genre = song.Genre.Type, 
          Year = song.Year, 
          Link = song.YoutubeLink, 
          Id = song.Id 

         }); 
        } 
       } 
      } 
      catch (Exception) 
      { 

       throw; 
      } 

      return View(songList); 
     } 

     public ActionResult Edit() 
     { 
      return View("Create"); 
     } 
    } 
} 

Это HTML:

@using System.Activities.Expressions 
@using System.Web.Mvc.Html 
@using MusicBox.Models 
@model IEnumerable<SongListViewModel> 

@{ 
    ViewBag.Title = "Popis"; 

} 

<h2>Popis pjesama</h2> 

<table class="table table-bordered"> 
    <thead class="thead"> 
    <tr> 
     <th> 
      Izvođač 
     </th> 
     <th> 
      Pjesma 
     </th> 

     <th> 
      Žanr 
     </th> 
     <th> 
      Godina 
     </th> 
     <th> 
      Youtube Link 
     </th> 
     <th> 

     </th> 
     <th> 

     </th> 
    </tr> 
    </thead> 
    <tbody> 
    @foreach (var item in Model) 
    { 
     <tr> 
      <td>@item.Performer</td> 
      <td>@item.Song</td> 
      <td>@item.Genre</td> 
      <td>@item.Year</td> 
      <td><a href="@item.Link" target="_b">Link</a></td> 
      <td> 
       @Html.ActionLink("Edit", "Edit", new {id = item.Id}) 
      </td> 
      <td> 
       <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirmSongDelete" data-songId="@item.Id"> 
        Briši 
       </button> 

      </td> 
     </tr> 
    } 
    </tbody> 

</table> 

<div class="modal fade" id="confirmSongDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> 
    <div class="modal-dialog" role="document"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <h5 class="modal-title" id="exampleModalLabel">Brisanje pjesme</h5> 
       <button type="button" class="close" data-dismiss="modal" aria-label="Close"> 
        <span aria-hidden="true">&times;</span> 
       </button> 
      </div> 
      <div class="modal-body"> 
       <p>Da li sigurno želite izbrisati?</p> 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-secondary" data-dismiss="modal">Odustani</button> 
       <button type="button" class="btn btn-primary">Obriši</button> 
      </div> 
     </div> 
    </div> 
</div> 
+0

вам нужно добавить метод удаления в контроллере – DaniDev

+0

Спасибо за быстрый ответ. Любые предложения, как это должно выглядеть? –

+0

оболочка вашего звонка будет выглядеть так же, как и другие ваши действия контроллера: общественного ActionResult Delete() { с использованием (вар дб = новая ApplicationDbContext()) { ........ } возвращение Посмотреть(); } – DaniDev

ответ

0

Было бы что-то вроде этого: -

Javascript

<script> 
    $(document).ready(function() { 
    $('#confirmSongDelete').on('show.bs.modal', function (e) { 
    var id = $(e.relatedTarget).attr('id'); 
    $("#btnConfirm").attr("id", id); 
    }); 
}) 

function DeleteSong(Id) { 

$("div[class='Success']").empty(); 
$("div[class='failure']").empty(); 
//call action method 
$("#confirmSongDelete").modal("hide"); 

$.ajax({ 
    url: "@Url.Action("DeleteSong", "HomeController")", 
    data: { id: Id }, 
    success: function (response) { 
     if (response != null && response == "True") { 
      $("#spnSuccessMsg").css("display", "block"); 
      $("#myModalOk").modal('show'); 

     } else { 
      $("#spnErrorMsg").css("display", "block"); 
      $("#myModalOk").modal('show'); 

     } 
     window.location.href = window.location.href; 
    } 
}); 
} 
</script> 

Посмотреть

@using System.Activities.Expressions 
@using System.Web.Mvc.Html 
@using MusicBox.Models 
@model IEnumerable<SongListViewModel> 

@{ 
ViewBag.Title = "Popis"; 
} 

<h2>Popis pjesama</h2> 

<table class="table table-bordered"> 
<thead class="thead"> 
<tr> 
    <th> 
     Izvođač 
    </th> 
    <th> 
     Pjesma 
    </th> 

    <th> 
     Žanr 
    </th> 
    <th> 
     Godina 
    </th> 
    <th> 
     Youtube Link 
    </th> 
    <th> 

    </th> 
    <th> 

    </th> 
</tr> 
</thead> 
<tbody> 
@foreach (var item in Model) 
{ 
    <tr> 
     <td>@item.Performer</td> 
     <td>@item.Song</td> 
     <td>@item.Genre</td> 
     <td>@item.Year</td> 
     <td><a href="@item.Link" target="_b">Link</a></td> 
     <td> 
      @Html.ActionLink("Edit", "Edit", new {id = item.Id}) 
     </td> 
     <td> 
      <button id="@item.Id" type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirmSongDelete" data-songId="@item.Id"> 
       Briši 
      </button> 

     </td> 
    </tr> 
} 
</tbody> 

</table> 

<div class="modal fade" id="confirmSongDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> 
<div class="modal-dialog" role="document"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
      <h5 class="modal-title" id="exampleModalLabel">Brisanje pjesme</h5> 
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"> 
       <span aria-hidden="true">&times;</span> 
      </button> 
     </div> 
     <div class="modal-body"> 
      <p>Da li sigurno želite izbrisati?</p> 
     </div> 
     <div class="modal-footer"> 
      <button id="btnConfirm" type="button" class="btn btn-secondary" data-dismiss="modal" onclick="DeleteSong(id);">Odustani</button> 
      <button type="button" class="btn btn-primary">Obriši</button> 
     </div> 
    </div> 
</div> 
</div> 

Контроллер

public bool DeleteSong() 
    { 
     int _deleteResult=0; 
     string _songId = Request.QueryString["id"]; 
     using (ApplicationDbContext db = new ApplicationDbContext()) 
     { 
     Song songsMaster = _context.Songs.Single(m => m.SongId == _songId); 
      _context.Songs.Remove(songsMaster); 
      _deleteResult= _context.SaveChanges(); 
     } 
     if(_deleteResult>0) 
     { 
     return true; 
     } 
     else 
     { 
     return false; 
     } 
    } 
+0

это не удалит песню из базы данных, ей необходимо вызвать метод контроллера – DaniDev

+0

Теперь проверьте метод удаления контроллера. – manika