Cześć, napotkałem problem który rozwiązałem ale chciałbym dowiedzieć się czy jest prostszy sposób na jego rozwiązanie. Rozwiązanie miało na celu utworzyć komunikat który wyświetli się po usunięciu rekordu i jednocześnie zostanie odświeżona tabela w widoku. Do tego celu użyłem Ajax helperów.

  • Główna akacja kontrolera: Korzystam tutaj z blibioteki do tworzenia paginacji, w której zwracam wszystkich lekarzy.**
 public ActionResult Lekarz(string sortBy, string searchWord, int? page)
        {
          
            int pageSize = 6;
            int currentPage = page.HasValue ? page.Value : 1; 

            ViewBag.sortName = String.IsNullOrEmpty(sortBy) ? "name_desc" : "";
            ViewBag.sortSurname = String.IsNullOrEmpty(sortBy) ? "surname_desc" : "";
            ViewBag.sortSpecialty = String.IsNullOrEmpty(sortBy) ? "specialty_desc" : "";
            ViewBag.sortEmail = String.IsNullOrEmpty(sortBy) ? " email_desc" : "";

            IList<Doctor> doctors = doctorService.SortListDoctors(sortBy).ToList();

            if (string.IsNullOrWhiteSpace(searchWord))
            {
                doctors = doctors.ToPagedList(currentPage, pageSize);
            }
            else
            {
                doctors = doctors.Where(p => p.Name.ToLower() == searchWord.ToLower()).ToPagedList(currentPage, pageSize);
            }
            

            if (Request.IsAjaxRequest())
                return PartialView("AjaxTabDoctor", doctors);
            else
                return PartialView(doctors);
        }
 

Widok wygląda tak: istotna część rozwiązani!!!

<script>
   function onDelete(result) {
        var id = result.id;
        $('#tab-doctors').html(result.dr);
        $.ajax({
            success: function (result) {         
                    if(confirm("Czy chesz usunąć lekarza?"))
                    {
                        $.ajax({
                            url: '/Reception/UsunPotwierdzenie/',
                            type: 'POST',
                            data: JSON.stringify({ id: id }),
                            contentType: "application/json",
                            success: function (json) {
                                $('#tab-doctors').html(json);
                                alert("Usunięto!");
                            }
                        });
                    }

            }
        });
    }

    function beginPaging(args) {
        // Animate
        $("#loader").fadeIn('normal');
    }

    function successPaging() {
        // Animate
        $('#loader').fadeOut('normal');
        $('a').tooltip();
      
    }

    function failurePaging() {
        alert("Could not retrieve list.");
    }
   
</script>
@using (Ajax.BeginForm("Lekarz", null,
                            new AjaxOptions { UpdateTargetId = "tab-doctors", HttpMethod = "get", LoadingElementId = "loading", OnBegin = "beginPaging", OnSuccess = "successPaging", OnFailure = "failurePaging" },
                            new { id = "frm-search" }))
{

<div style="padding:20px 0px 5px 5px;">
        <div style="display:inline-block;">Poniżej prezentowana jest lista wszystkich pracujących lekarzy w klinice. Możesz dodawać usuwać i edytować lekarzy!</div>
        <div style="display:inline-block;margin-left:120px;">
            <input class="span2" id="appendedInputButton" type="text" style="width:200px;height:24px;" name="searchWord" placeholder="Podaj imię" />
            <button class="button" type="submit" style="padding: 3px; margin: 0; border-radius: 0px;width:80px;">
                <i class="icon-search"></i>&nbsp;SZUKAJ
            </button>
        </div>
</div>

}
<div id="tab-doctors" style="border: 8px solid rgba(77, 172, 132, 0.43);">
    @{ Html.RenderPartial("AjaxTabDoctor", Model); }
</div>
@Html.ActionLink("Dodaj lekarza", "Dodaj", "Reception")

 

PartialView AjaxTabDoctor: Tutaj użyłem Ajax.ActionLink w którym dodałem właściwosci takie jak : UpdateTargetId , onSuccess

 

@using MvcPaging
@model IPagedList<ServiceRepository.Models.Doctor>


<div id="loader" style="position: absolute;background:red;"></div>
<table class="table" id="IdTab" style="box-shadow: 0px 1px 6px -2px #838383;width:100%;">
    <thead>
        <tr>
            <td>@Html.ActionLink("Imie", "Lekarz", new { sortBy = ViewBag.sortName })</td>
            <td>@Html.ActionLink("Nazwisko", "Lekarz", new { sortBy = ViewBag.sortSurname })</td>
            <td>@Html.ActionLink("Specjalność", "Lekarz", new { sortBy = ViewBag.sortSpecialty })</td>
            <td>@Html.ActionLink("Email", "Lekarz", new { sortBy = ViewBag.sortEmail })</td>
            <td>Telefon</td>
            <td>Opcje</td>
        </tr>
    </thead>
    @if (Model.ToList().Count == 0)
    {
        <tr>
            <td style="text-align:center">Brak</td>
            <td style="text-align:center">Brak</td>
            <td style="text-align:center">Brak</td>
            <td style="text-align:center">Brak</td>
            <td style="text-align:center">Brak</td>
            <td style="text-align:center">Brak</td>
        </tr>

    }
    @foreach (var doctor in Model)
    {
        <tr>
            <td style="text-align:center">
                @doctor.Name
            </td>
            <td style="text-align:center">
                @doctor.Surname
            </td>
            <td style="text-align:center">
                @doctor.Specialty
            </td>
            <td style="text-align:center">
                @doctor.Email
            </td>
            <td style="text-align:center">
                @doctor.Phone
            </td>
            <td style="text-align:center;">
                @Ajax.ActionLink("Usuń", "Usun", "Reception", new { id = @doctor.DoctorID }, new AjaxOptions() { UpdateTargetId = "tab-doctors", HttpMethod = "POST", OnSuccess = "onDelete" }, new { @class = "button", Style = "display:inline-block;width:70px;" })
                @Ajax.ActionLink("Edytuj", "Edytuj", "Reception", new { id = @doctor.DoctorID }, new AjaxOptions { UpdateTargetId = "tab-doctors", HttpMethod = "POST" }, new { @class = "button", Style = "display:inline-block;width:70px;" })
                @*@Html.ActionLink("Usuń", "Usun", "Reception", new { id = @doctor.DoctorID}, new { @class = "button", Style = "display:inline-block;width:70px;" })*@
            </td>
        </tr>
    }
</table>

**Metody Usun i UsunPotwierdzenie **

 
       [HttpPost]
        public JsonResult Usun(int id = 0)
        {
            Doctor doctor = doctorService.GetDoctorByID(id);
            if (doctor == null)
            {
                return Json(null);
            }
            IList<Doctor> doctors = doctorService.SortListDoctors().ToList();
            doctors = doctors.ToPagedList(1, 6);
            var tab = RenderPartialViewToString("AjaxTabDoctor", doctors);
            return Json(new { dr = tab, id = id }, JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public JsonResult UsunPotwierdzenie(int id)
        {            
            try
            {
                Doctor doctor = doctorService.GetDoctorByID(id);
                int userId = doctorService.GetDoctorUserId(id);
                userService.DeleteUser(userId);
                userService.Save();

                IList<Doctor> doctors = doctorService.SortListDoctors().ToList();
                doctors = doctors.ToPagedList(1, 6);
                var tab = RenderPartialViewToString("AjaxTabDoctor", doctors);
                return Json(tab ,JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "Wystąpił błąd, proszę skontaktować się z administratorem. Typ błędu:" + ex.Message);

            }

            return Json("",JsonRequestBehavior.AllowGet);
        }

Metoda odpowiedzialna za przerobienie PartialView - czyli "AjaxTabDoctor" na stringa i wysłanie Jsonem do widoku.

 
 public string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

Czy znacie jaką prostszą implementacje potwierdzenia usunięcia rekordu z odświeżeniem tabeli(PartialView)?