I want to call java script after clicking <a> tag in my partial view, it is working for the first time but second time after using ajax and rendering my partial view, it doesn't go to <a> tag event. let just show my code to let you grasp it better. this is my parent view:
#using X.PagedList
#using X.PagedList.Mvc.Core
#using X.PagedList.Mvc.Core.Common
#model X.PagedList.IPagedList<Services.ViewModel.Admin.Nurse.NurseDetailsViewModel>
#{
ViewData["Title"] = "RegisteredNurseList";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
// LOT OF HTML TAG CODE HERE I JUST IGNOR THEM...
<section id="table-transactions">
<!-- datatable start -->
<div id="nursesList">
<partial name="PaginatedNurses" model="Model" />
</div>
<!-- datatable ends -->
</div>
</section>
#section modalSection
{
<script>
window.$(document).ready(function () {
window.$('#RegisteredNursePaginated').find('a[href]').on('click',
function (e) {
e.preventDefault();
var sortOrder = window.$("#sortOrder").val();
var sortType = window.$("#sortType").val();
var minAge = window.$("#minAge").val();
var maxAge = window.$("#maxAge").val();
var page = getQueryStringValue(this, 0).replace('page=', '');
// window.$("#pageGetter").val(page);
debugger;
console.log(this);
window.$.ajax({
url: "/admin/RegisteredNurseList/",
type: 'GET',
data: {
page: page,
SortOrder: sortOrder,
sortType: sortType,
MinAge: minAge,
MaxAge: maxAge
},
success: function (result) {
debugger;
window.$('#RegisteredNursePaginated').html(result);
}
});
return false;
});
});
</script>
}
as you see I am using <partial name="PaginatedNurses" model="Model" /> to call partial view. and this is my PaginatedNurses partial view :
#using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
#using X.PagedList
#using X.PagedList.Mvc.Core
#using X.PagedList.Mvc.Core.Common
#model X.PagedList.IPagedList<Services.ViewModel.Admin.Nurse.NurseDetailsViewModel>
<body>
<form>
<div id="RegisteredNursePaginated">
<div class="form-group row">
<div class="col-md-3">
از سن <input class="form-control" id="minAge" type="number" name="MinAge" value="#ViewBag.MinAge" />
</div>
<div class="col-md-3">
تا سن <input class="form-control" id="maxAge" type="number" name="MaxAge" value="#ViewBag.MaxAge" />
</div>
<div class="col-md-3">
مرتب سازی بر اساس
<select class="form-control" name="SortOrder" value="#ViewBag.SortOrder" style="width: 200px" id="sortOrder">
<option value="age">
سن
</option>
<option value="registerDate">
زمان ثبت نام
</option>
</select>
</div>
<div class="col-md-3">
نحوه مرتب سازی
<select class="form-control" name="SortType" value="#ViewBag.SortType" style="width: 200px" id="sortType">
<option value=1>
صعودی
</option>
<option value=0>
نزولی
</option>
</select>
</div>
</div>
<input type="submit" value="جست و جو" id="btnSearch" />
<div class="table-responsive">
<table id="table-extended-transactions" class="table mb-0">
<thead>
<tr>
<th>نام</th>
<th>سن</th>
<th>شماره پروانه کار</th>
#*<th>شماره ملی</th>*#
<th>دوره حرفه ای</th>
<th>تاریخ ثبت نام</th>
</tr>
</thead>
<tbody>
#foreach (var nurse in Model)
{
<tr>
<td><i class="bx bxs-circle success font-small-1 mr-50 align-middle"></i><span>#nurse.FullName</span></td>
<td class="text-bold-700">#nurse.Age</td>
<td class="text-bold-700">#nurse.NurseSystemNumber</td>
<td>
#nurse.ProfessionalCourseDescription
</td>
<td>
#nurse.SubmissionDatePersian
</td>
<td>
<div class="dropdown">
<span class="bx bx-dots-horizontal-rounded font-medium-3 dropdown-toggle nav-hide-arrow cursor-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" role="menu">
</span>
<div class="dropdown-menu">
<a class="dropdown-item" href="#Url.Action("NurseDetails", "Admin", new {id = #nurse.Id})"><i class="bx bx-edit-alt mr-1"></i> نمایش جزئیات</a>
<a class="dropdown-item" onclick="setInvitation('#nurse.Id')">تایید</a>
<a class="dropdown-item" onclick="refuseRegister('#nurse.Id')"><i class="bx bx-trash mr-1"></i>عدم تایید</a>
</div>
</div>
</td>
</tr>
}
</tbody>
</table>
<div id="pager">
<input value="1" type="hidden" id="pageGetter"/>
#Html.PagedListPager((IPagedList) Model, page =>
Url.Action("RegisteredNurseList",
new
{
page = page,
SortOrder = ViewBag.SortOrder,
SortType = ViewBag.SortType,
MaxAge = ViewBag.MaxAge,
MinAge = ViewBag.MinAge
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new AjaxOptions() {HttpMethod = "GET", UpdateTargetId = "RegisteredNursePaginated"}))
</div>
</div>
</div>
</form>
</body>
as you witness there is html tag helper #Html.PagedListPager((IPagedList) Model,... this is using <a> tag. I Mean after clicking on this, it is going to parent modelSection:
<script>
window.$(document).ready(function () {
window.$('#RegisteredNursePaginated').find('a[href]').on('click',
function (e) {
e.preventDefault();
var sortOrder = window.$("#sortOrder").val();
var sortType = window.$("#sortType").val();
var minAge = window.$("#minAge").val();
var maxAge = window.$("#maxAge").val();
var page = getQueryStringValue(this, 0).replace('page=', '');
// window.$("#pageGetter").val(page);
debugger;
console.log(this);
window.$.ajax({
url: "/admin/RegisteredNurseList/",
type: 'GET',
data: {
page: page,
SortOrder: sortOrder,
sortType: sortType,
MinAge: minAge,
MaxAge: maxAge
},
success: function (result) {
debugger;
window.$('#RegisteredNursePaginated').html(result);
}
});
return false;
});
});
</script>
it works first time but after using ajax and rendering it by controller, it will never go to that part again after clicking <a> tag. this is my controller:
public async Task<IActionResult> RegisteredNurseList(int? page, int? sortType, string sortOrder,
int? minAge, int? maxAge)
{
bool isAjax = HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
ViewBag.PageNumber = page ?? 1;
int pageSize = 2;
int skip = (ViewBag.PageNumber - 1) * pageSize;
ViewBag.MinAge = minAge ?? 18;
ViewBag.MaxAge = maxAge ?? 99;
ViewBag.SortType = sortType ?? 1;
ViewBag.SortOrder = sortOrder ?? "age";
var tuple = await _admin.GetNurses(skip, pageSize, sortOrder ?? "age", sortType ?? 1, minAge ?? 18, maxAge ?? 99);
int total = tuple.Item2;
var nurses = tuple.Item1;
var result = new StaticPagedList<NurseDetailsViewModel>(nurses, ViewBag.PageNumber, pageSize, total);
if (isAjax)
{
return (ActionResult)PartialView("PaginatedNurses", result);
}
return View(result);
}
after #steve perfect comment I got his idea and I changed my code like below and then it worked:
<script>
function AjaxInit() {
window.$('#RegisteredNursePaginated').find('a[href]').on('click',
function (e) {
e.preventDefault();
var sortOrder = window.$("#sortOrder").val();
var sortType = window.$("#sortType").val();
var minAge = window.$("#minAge").val();
var maxAge = window.$("#maxAge").val();
var page = getQueryStringValue(this, 0).replace('page=', '');
// window.$("#pageGetter").val(page);
debugger;
console.log(this);
window.$.ajax({
url: "/admin/RegisteredNurseList/",
type: 'GET',
data: {
page: page,
SortOrder: sortOrder,
sortType: sortType,
MinAge: minAge,
MaxAge: maxAge
},
success: function (result) {
debugger;
window.$('#RegisteredNursePaginated').html(result);
}
});
return false;
});
}
</script>
<script>
window.$(document).ready(function () {
AjaxInit();
});
</script>
<script>
$(document).ajaxComplete(function () {
AjaxInit();
});
</script>
Related
I have a Partial View as a Table, that will be refreshed with a Dropdown Selection in the Main View. This dropdown list includes company names. In the table below information matters pertaining to each company, and for each line of this information there is a drop-down list of all the functions that I can do with this line (like deleting or modifying the information) with a Pop-up Modal.
How can I call a Method in the main Model or Submit something? Or can I create a Partial View with Model in my Case?
Here is my Main View:
#page
#model Fachinformationsdienst_Kundenportal.Pages.Information_listModel
#{
}
<form>
<div class="form-row align-items-center">
<div class="form-group col-md-4">
<label for="inputState">Wählen Sie eine Unternehmen aus</label>
<select id="inputState" class="form-control">
#for (int i = 0; i < Model.companies.Count; i++)
{
<option>#Model.companies[i].FirmenKurzBezeichnung</option>
}
</select>
</div>
<div class="form-group col-md-6">
<input class="form-control" id="myInput" type="text" style="margin-top: 31px;" placeholder="Suche...">
</div>
<div class="form-group col-md-2">
<button type="button" class="btn btn-primary" style="margin-top: 31px;">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</form>
<div id="fachinfoContainer">
<partial name="_FachinfoPartial" model="#Model.myViewModel" />
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$("#inputState").change(function () {
var selectcompany = "";
if ($(this).val() != "Wählen Sie die Firma aus...") {
selectcompany = $(this).val();
}
$.ajax({
url: "/Actions/Information-List?handler=fachinfoPartial",
type: "Get",
data: { company: selectcompany },
success: function (result) {
$("#fachinfoContainer").html(""); //clear the fachinfo container.
$("#fachinfoContainer").html(result); //populate the container.
},
error: function (result) {
alert(result);
}
});
});
});
</script>
}
Here is my Partial View
#model Fachinformationsdienst_Kundenportal.Models.MyViewModel
<table class="table table-striped" id="FachinfoTable">
<thead>
<tr>
<th scope="col">Nr.</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Letzte Änderung</th>
<th scope="col">Aktuelle Version</th>
<th scope="col">Auftrag</th>
</tr>
</thead>
<tbody id="myTable">
#if (#Model.Fachinfos != null)
{
#for (int i = 0; i < #Model.Fachinfos.Count; i++)
{
<tr>
<th scope="row">#Model.Fachinfos[i].FachinfoNummer</th>
<td>#Model.Fachinfos[i].FachinfoName</td>
<td>#Model.Fachinfos[i].Status</td>
<td>#Model.Fachinfos[i].Datum</td>
<td>#Model.Fachinfos[i].PdfVersion</td>
<td>
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#for (int c = 0; c < #Model.SelectedCompany.Permissions.Count; c++)
{
if (Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ERSTERFASSEN && Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ABFRAGEN)
{
<a class="dropdown-item" data-toggle="modal" data-number="#Model.Fachinfos[i].FachinfoNummer" data-version="#Model.Fachinfos[i].PdfVersion" data-target="##Model.SelectedCompany.Permissions[c]">#Model.SelectedCompany.Permissions[c]</a>
}
}
</div>
</div>
</td>
</tr>
}
}
</tbody>
</table>
<!-- The Delete Modal -->
<div class="modal fade" id="#Models.Company.Permission.LOESCHEN">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Bestätigen</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<span id="deletMessege">Sind Sie sicher, dass Sie diese Fachinformation löschen möchten?</span>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="confirm" type="submit" class="btn btn-primary">Senden</button>
</div>
</div>
</div>
</div>
<script>
$('##Models.Company.Permission.LOESCHEN').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var fiNumber = button.data('number') // Extract info from data-* attributes
var modal = $(this)
modal.find('.modal-title').text('Fachinfonummer ' + fiNumber)
})
</script>
Here is my main model
using Fachinformationsdienst_Kundenportal.Classes;
using Fachinformationsdienst_Kundenportal.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
namespace Fachinformationsdienst_Kundenportal.Pages
{
public class Information_listModel : PageModel
{
public List<Company> companies { get; set; }
public List<Fachinfo> fachinfos = new List<Fachinfo>();
public MyViewModel myViewModel = new MyViewModel();
public void OnGet()
{
companies = APIRequester.GetCompanies(User.Identity.Name);
foreach (var company in companies)
{
fachinfos.AddRange(APIRequester.GetFachinfos(company.FirmenKurzBezeichnung));
}
}
public PartialViewResult OnGetFachinfoPartial(string company)
{
//based on the selctedcompany to filter data, then return to the partial view.
companies = APIRequester.GetCompanies(User.Identity.Name);
myViewModel = new MyViewModel()
{
SelectedCompany = companies.Find(r => r.FirmenKurzBezeichnung == company), //get the company object here
Fachinfos = APIRequester.GetFachinfos(company)
};
return Partial("_FachinfoPartial", myViewModel);
}
//Submit this Method from Partial view
public IActionResult onDelete(string fiNumber)
{
return Page();
}
}
}
You can use JQUERY AJAX calls for this
$.ajax({
type: "POST",
url: '/Information_listModel?handler=Ondelete',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data.result);
})
your method should return type IActionResult
I am learning ajax requests and I was wondering if I am doing right here. Well I have a page which include pagination, sorting and searching. I am trying to get this by ajax because I don't want to load the whole page again. so this is part of my parent view :
.
..
<div id="nursesList">
#Html.Partial("PaginatedNurses", Model)
</div>
...
And this is my partial which I try to use ajax:
#using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
#using X.PagedList
#using X.PagedList.Mvc.Core
#using X.PagedList.Mvc.Core.Common
#model X.PagedList.IPagedList<Services.ViewModel.Admin.Nurse.NurseDetailsViewModel>
<form>
<div id="RegisteredNurses">
<div class="form-group row">
<div class="col-md-3">
از سن <input class="form-control" id="minAge" type="number" name="MinAge" value="#ViewBag.MinAge" />
</div>
<div class="col-md-3">
تا سن <input class="form-control" id="maxAge" type="number" name="maxAge" value="#ViewBag.MaxAge" />
</div>
<div class="col-md-3">
مرتب سازی بر اساس
<select class="form-control" name="SortOrder" value="#ViewBag.SortOrder" style="width: 200px" id="sortOrder">
<option value="age">
سن
</option>
<option value="registerDate">
زمان ثبت نام
</option>
</select>
</div>
<div class="col-md-3">
نحوه مرتب سازی
<select class="form-control" name="SortType" value="#ViewBag.SortType" style="width: 200px" id="sortType">
<option value=1>
صعودی
</option>
<option value=0>
نزولی
</option>
</select>
</div>
</div>
<input type="submit" value="جست و جو" id="btnSearch" />
<div class="table-responsive">
<table id="table-extended-transactions" class="table mb-0">
<thead>
<tr>
<th>نام</th>
<th>سن</th>
<th>شماره پروانه کار</th>
#*<th>شماره ملی</th>*#
<th>دوره حرفه ای</th>
<th>تاریخ ثبت نام</th>
</tr>
</thead>
<tbody>
#foreach (var nurse in Model)
{
<tr>
<td><i class="bx bxs-circle success font-small-1 mr-50 align-middle"></i><span>#nurse.FullName</span></td>
<td class="text-bold-700">#nurse.Age</td>
<td class="text-bold-700">#nurse.NurseSystemNumber</td>
<td>
#nurse.ProfessionalCourseDescription
</td>
<td>
#nurse.SubmissionDatePersian
</td>
<td>
<div class="dropdown">
<span class="bx bx-dots-horizontal-rounded font-medium-3 dropdown-toggle nav-hide-arrow cursor-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" role="menu">
</span>
<div class="dropdown-menu">
<a class="dropdown-item" href="#Url.Action("NurseDetails", "Admin", new {id = #nurse.Id})"><i class="bx bx-edit-alt mr-1"></i> نمایش جزئیات</a>
<a class="dropdown-item" onclick="setInvitation('#nurse.Id')">تایید</a>
<a class="dropdown-item" onclick="refuseRegister('#nurse.Id')"><i class="bx bx-trash mr-1"></i>عدم تایید</a>
</div>
</div>
</td>
</tr>
}
</tbody>
</table>
<div id="pager">
#Html.PagedListPager((IPagedList)Model, page => Url.Action("RegisteredNurseList", new { page}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "RegisteredNurses" }))
</div>
</div>
</div>
</form>
#section modalSection
{
<script src="~/js/jquery.unobtrusive-ajax.min.js"></script>
}
Main part is here:
<div id="pager">
#Html.PagedListPager((IPagedList)Model, page => Url.Action("RegisteredNurseList", new { page}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "RegisteredNurses" }))
</div>
I want to add the value of inputs in my dom. For example:
<div id="pager">
#Html.PagedListPager((IPagedList)Model, page => Url.Action("RegisteredNurseList", new { page , sortOrder=('#sortOrder').val()}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "RegisteredNurses" }))
</div>
I know this sortOrder=('#sortOrder').val() is not a valid code, but I want to find an alternative for this or even any better approach.
This is my controller:
public async Task<ActionResult> RegisteredNurseList(int? page, int? sortType,string sortOrder,
int? minAge, int? maxAge)
{
bool isAjax = HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
int pageNumber = page ?? 1;
int pageSize = 2;
int skip = (pageNumber - 1) * pageSize;
ViewBag.MinAge = minAge ?? 18;
ViewBag.MaxAge = maxAge ?? 99;
ViewBag.sortType = sortType ?? 1;
ViewBag.SortOrder = sortOrder;
var tuple = await _admin.GetNurses(skip, pageSize, sortOrder, sortType ?? 1, minAge ?? 18, maxAge ?? 99);
int total = tuple.Item2;
var nurses = tuple.Item1;
var result = new StaticPagedList<NurseDetailsViewModel>(nurses, pageNumber, pageSize, total);
if (isAjax)
{
return (ActionResult) PartialView("PaginatedNurses", result);
}
return View(result);
}
My answer here will help you: https://stackoverflow.com/a/50727347/177416
You want to capture the user's clicking of a page number in the pager control and rewrite the link before letting it through. This is done on the client via JavaScript onClick handler on the page numbers; the following handler goes in your jQuery document ready event handler:
$('#pager').find('a[href]').on('click', function (e) {
e.preventDefault();
location.href = this.split('?')[0]
+ "?page=" + getQueryStringValue(this, 0).replace('page=','')
+ "&sortOrder=" + $("#sortOrder").val(); // Add other values if needed
}
});
Here's the helper function:
getQueryStringValue: function (anchor, index) {
var queryString = $(anchor).attr('href').split('?')[1];
var values = queryString.split('&');
return values[index];
}
This line gets us the raw URL without the querystring; this in this case is the URI:
this.split('?')[0]
Setting location.href is like clicking a link; it'll redirect the page to the indicated URI.
I've been wanted to delete the row by its id.
I've already done "things" in Service, Controller, Listfiles, and the Delete file.
This is the controller
#RequestMapping("/hapussertifikasi")
public String hapussertifikasi() {
return ("sertifikasi/hapussertifikasi");
}
#ResponseBody
#RequestMapping(value = "/hapussertifikasi/{angka}", method = RequestMethod.DELETE)
public Map<String, String> hapussertifikasi(#PathVariable("angka") Long angka, Model model) {
sertifikasisr.hapus(angka);
// key value
Map<String, String> map = new HashMap<>();
// pakai String string karena value key dan value nya string
System.out.println();
System.out.println(angka);
map.put("status", "berhasil");
// DARI BARANG SERVICE
/*
* if(brngsr.hapus(angka)) { // key value map.put("status", "berhasil"); }else {
* map.put("status", "gagal"); }
*/
return map;
}
This is the Service file
public boolean hapus(Long id) {
try {
sertifikasi.deleteById(id);
return true;
}catch(Exception e) {
return false;
}
}
This is the List File
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<!-- Nulis table didalam body -->
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<td>ID</td>
<td>Nama Sertifikasi</td>
<td>Penerbit</td>
<td>Masa Berlaku</td>
<td>#</td>
</tr>
</thead>
<tbody id="idTbodySertifikasi">
<tr th:each="item :${keysertifikasi}">
<td th:text="${item.id}">ID</td>
<td th:text="${item.certificate_name}">NamaBarang</td>
<td th:text="${item.publisher}">JenisBarang</td>
<td th:text="${item.until_year + '-' + item.until_month }">Sampai</td>
<td>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button"
data-toggle="dropdown">
More <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li class="clDropdown" data-value="0">Ubah</li>
<li class="clDropdown" data-value="1">Hapus</li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$('.table-responsive').on('show.bs.dropdown', function() {
$('.table-responsive').css("overflow", "inherit");
});
$('.table-responsive').on('hide.bs.dropdown', function() {
$('.table-responsive').css("overflow", "auto");
});
$(".clDropdown").click(function() {
debugger;
var x = $(this).data('value');
var angka = $(this).attr('data-idbarang');
if (x == 0) {
$.ajax({
url : './ubahsertifikasi',
method : 'Get',
success : function(model) {
debugger;
/* jahit model return dari controller ke body modal */
$('#idMdlBodyUbahSertifikasi').html(model);
/* pop up modalnya */
$('#idMdlUbahSertifikasi').modal('show');
},
error : function(model) {
debugger;
}
});
} else if (x == 1) {
debugger;
$.ajax({
url : './hapussertifikasi',
method : 'Get',
success : function(model) {
debugger;
/* jahit model return dari controller ke body modal */
$('#idMdlBodyHapusSertifikasi').html(model);
/* pop up modalnya */
$('#idMdlHapusSertifikasi').modal('show');
},
error : function(model) {
debugger;
}
});
}
});
</script>
</body>
</html>
And lastly this is the delete file where the delete button is placed
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="col-xs-12">
<div class="row">
<div class="col-xs-2">
<i class="glyphicon glyphicon-trash center" style="font-size: 50px"></i>
</div>
<div class="col-xs-8">
<div class="clTulisanHapus center" id="idTulisanHapus">Anda
Yakin ingin menghapus Pelatihan?</div>
</div>
</div>
</div>
<div class="col-md-offset-8">
<div class="btn-group">
<button type="button" id="idBtnHapusBatal" class="btn clBtnMdlHapus">Tidak</button>
<button type="button" id="idBtnHapusHapus" class="btn clBtnMdlHapus">Ya</button>
</div>
</div>
<script>
$('#idBtnHapusHapus').click(function() {
var angka = $(this).attr('data-id');
debugger;
debugger;
$.ajax({
url : '/hapussertifikasi/' + angka,
type : 'DELETE',
success : function(model) {
debugger;
window.location = './sertifikasi'
},
error : function(model) {
debugger;
}
});
});
</script>
</body>
</html>
The id is showing ok, but the id values isn't sending to the Controller file.
The button <button type="button" id="idBtnHapusHapus" class="btn clBtnMdlHapus">Ya</button> has no data-id attribute, thus when calling var angka = $(this).attr('data-id');, angka is Nil.
This means you are making a delete request on /hapussertifikasi/, which is going to return a 400 error because you aren't passing the required argument (correct syntax would be /hapussertifikasi/14 where 14 is the id you want to delete.)
hi bro i also face this type of problem .....
after longtime R&D i found a solution , but i don't know why it's working..
try this
url : 'hapussertifikasi/' + angka,
just remove first /sing
In the view (Index.cshtml) I have a button, when I click on that, the script that in the selectedItems writes the data is triggered. how are selectedItems transferred to the controller?
Button:
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
JS:
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
}
Controller (Users):
[HttpPost]
public async Task<ActionResult> Delete(string[] selectedUsers)
{
...
return RedirectToAction("Index");
}
I tried to use ajax, but something does not work out:
function SelectedCheckbox()
{
$.ajax({
url: "/Users",
contentType: "application/json",
method: "POST",
data: { parameters: parameters },
success: function (data) {
var data = new Array();
$("input[id='check']:checked").each(function () { data.push($(this).val()); });
alert(data.result);
},
error: function (data) { alert(data.responseText); }
})
}
#model IEnumerable<Task1.Models.User>
#{
ViewBag.Title = "Список пользователей";
}
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="btn-toolbar nl container col-md-12" role="toolbar" aria-label="Menu">
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" name="delete" id="delete" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
<form method="post" asp-controller="Account" asp-action="LogOff">
<button type="submit" class="col-md-2 col-md-offset-3 " role="group" aria-label="LogOff" />LogOff</button>
</form>
</div>
<form asp-action="Delete">
<div class="nl">
<table class="table table-striped table-bordered ">
<tbody class="table-responsive ">
<tr><th><input type="checkbox" class="all" data-id="d1" title="Выбрать все"></th><th>Login</th><th>Date of registration</th><th>Date Last Login</th><th>Block disabled</th></tr>
#foreach (var user in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedUsers"
id="#user.Id" value="#user.Id"
class="styled">
</td>
<td>#user.UserName</td>
<td>#user.DateOfRegistration</td>
<td>#user.DateLastLogin</td>
<td>#user.LockoutEnabled</td>
</tr>
}
</tbody>
</table>
</div>
</form>
<script type="text/javascript">
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
alert(selectedItems);
return (selectedItems);
}
</script>
I need to pass the value of the selected Item from the script in the method of removing the controller
I'm looking to build an book shelf application which add, removes, edits books shelf data using angular routing.
But when I try to prepopulate a record to edit it, I'm not able to get the prepopulated values.
I have tried to assign value using $scope.{model name}. but it is not working
App.js
var myApp = angular.module('myApp', []);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/viewBook',
{ template : '<div ng-controller="ViewBookController"> <h2>Books</h2> <table class="table table-bordered table-condensed"> <thead> <tr> <td>Name</td> <td>Category</td> <td>Price</td> <td>Actions</td> </tr> </thead> <tr ng-repeat ="book in books"> <td>{{book.name}}</td> <td>{{book.category}}</td> <td>{{book.price}}</td> <td><span class="glyphicon glyphicon-edit">Edit</span> | <span class="glyphicon glyphicon-trash">Delete</span> </td> </tr> </table> </div>',
controller : 'ViewBookController'}).
when('/addBook',
{ template : '<div ng-controller = "ViewBookController"> <form class="well"> <label>Name*</label> <input type="text" name="name" ng-model="addBook.name" /><br/> <label>Category*</label> <input type="text" name="email" ng-model="addBook.category" /><br/> <label>Price*</label> <input type="text" name="phone" ng-model="addBook.price" /><br/> <br/> <input type="hidden" ng-model="addBook.id"/> <button ng-click ="add(addBook)">Add </button> <button type="button" class="btn btn-danger"><a href="#/viewBook">Cancel</button> </form> </div> ',
controller : 'ViewBookController'}).
otherwise({redirectTo: '/viewBook'});
}]);
myApp.controller('ViewBookController', function($scope, ViewBookService) {
$scope.tempbook ="";
$scope.books = ViewBookService.list();
$scope.delete = function (id) {
ViewBookService.delete(id);
// if ($scope.addBook.id == id)
// $scope.addBook = {};
}
$scope.add = function() {
ViewBookService.save($scope.addBook);
$scope.addBook = {};
alert('book added successfully');
}
$scope.edit = function (addBook,id) {
//$scope.addbook = $scope.tempbook;
$scope.addBook= (angular.copy(ViewBookService.get(id)));
}
});
myApp.service('ViewBookService', function() {
//to create unique book id
var uid = 3;
//books array to hold list of all books
var books = [{
id : 0,
name : 'Java',
category : 'software',
price : 600,
},
{
id : 1,
name : 'Sherlock Holmes',
category : 'fiction',
price : 350,
},
{
id : 2,
name : 'Wings of Fire',
category : 'autobiography',
price : 250,
}];
//save method create a new book if doesnt exist else update the existing object
this.save = function(book) {
if(book.id == null) {
book.id =uid++;
books.push(book)
}
else {
for(i in books) {
if(books[i].id == book.id) {
books[i] ==book;
}
}
}
}
//simply search books list for given id and returns the book object if found
this.get = function(id) {
for(i in books) {
if( books[i].id == id) {
return books[i];
}
}
}
//iterate through books list and delete book if found
this.delete = function (id) {
for (i in books) {
if (books[i].id == id) {
books.splice(i, 1);
}
}
}
//simply returns the books list
this.list = function () {
return books;
}
});
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
</body>
</html>