I want to call Action to open up my Index View by Ajax Javascript, but it does not load target view. Before I use ajax I called action like this that work properly:
<a class="btn btn-orange" href="#Url.Action("Index", "Booking", new { area = "Portal" })">انتخاب</a>
But I need to call with javascript Ajax and when I transfer that to this :
<a class="btn btn-orange" onclick="Booking(#Json.Encode(item))">انتخاب</a>
I faced this problem that it does not load page.
This is my ajax code:
function Booking(obj) {
var schedulingViewModel = {
};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
schedulingViewModel[key] = obj[key];
}
}
$.ajax({
url: '/Portal/Booking',
type: 'post',
data: schedulingViewModel,
success: function (data) {
alert('Data: ' + data);
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
}
And this s my BookingController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tranship.ViewModel;
namespace Tranship.UI.Areas.Portal.Controllers
{
public class BookingController: Controller
{
[HttpPost]
public ActionResult Index(ScheduleViewModel schedulingViewModel)
{
return View("Index", schedulingViewModel);
}
}
}
This is my view with IEnumerable model that I want to send an Item of that to action:
#model IEnumerable<Tranship.ViewModel.ScheduleViewModel>
<div class="pg-search-form">
#foreach (var item in Model)
{
<div class="list-block main-block f-list-block dashboard-listing booking-listing">
<div class="list-content">
<table class="table table-hover">
<tbody>
<tr>
<td class="dash-list-icon booking-list-date">
<div class="b-date">
<h3>#item.DepartureDay</h3>
<p>#item.DepartureMonth</p>
</div>
</td>
<td class="dash-list-text booking-list-detail">
<h3>#item.Origin به #item.Destination</h3>
<ul class="list-unstyled booking-info">
<li>#item.DepartureDate<span>تاریخ رفت :</span></li>
<li>#item.ArrivalDate<span>تاریخ برگشت :</span></li>
<li>#item.Adult نفر<span>تعداد :</span></li>
</ul>
</td>
<td class="dash-list-btn">
<a class="btn btn-orange" onclick="BookingMethod(#Json.Encode(item))">انتخاب</a>
#*<button type="submit" class="btn btn-orange">انتخاب</button>*#
#*<a class="btn btn-orange" href="#Url.Action("Index", "Booking", new { area = "Portal" })">انتخاب</a>*#
<div id="price">#item.Price تومان</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end list-content -->
</div>
}
<div class="pages">
<ol class="pagination">
<li><span aria-hidden="true"><i class="fa fa-angle-left"></i></span></li>
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li><span aria-hidden="true"><i class="fa fa-angle-right"></i></span></li>
</ol>
</div>
<!-- end pages -->
</div>
In fact ajax return correct HTML but I couldn't find why it does not redirect to target view.
window.location() is used to redirect from one page to another page.
After Successful ajax request write that code.
$.ajax({
url: '/Portal/Booking',
type: 'post',
data: schedulingViewModel,
success: function (data) {
alert('Data: ' + data);
window.location = "/Booking/Index";
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
Related
I'm working on a page where i'm rendering data from an api, where i make dynamic profile cards. And on clicking the button inside the card i'm calling an api through ajax. my problem is i need two values to pass to req.body to make the ajax success. I mananged the api call using one data using this code,
<div class="container" id="bb1">
<% locals.posts.rows.forEach(function (patient) { %>
<div class="patient-data">
<div >
<div style="padding-left: 100px"> <img src="<%= patient.dp %>" style="width: 45%;"> </div>
<br>
<div style="text-align: center;">
<h5> P.ID : <%= patient.p_id %></h5>
<p> Name : <%= patient.patient_name %></p>
</div>
<div style="padding-left: 110px;margin-bottom:20px ;">
<button type = "button" id="<%= patient.p_id %>" onclick="approve(this.id)" type="button" class="btn btn-info btn-sm" id="btn-success" style="background-color: #D1B147;"> View</button> </a></div>
</div>
</div>
<% }); %>
</div>
then inside my script;
<script type="text/javascript">
function approve(id) {
var p_id = id;
console.log(p_id);
var data = {};
data.p_id = p_id;
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
dataType: 'json',
url: "http://localhost:5000/mData",
success: function(data) {
console.log(data);
localStorage.setItem('myData', JSON.stringify(data));
window.location.href = 'mastersessionhistory';
},
error: function(){
alert("Error")
console.log('error occured')
}
})
}
</script>
using this i was able to hit api and return values. i needed only the p_id to hit api. But now i have new key m_id to so my req.body should be {p_id,m_id}. How to include m_id on that bitton click so that i can call the api.
can i use this
<button type = "button" id="<%= patient.p_id, patient.m_id%>" onclick="approve(this.id)" type="button" class="btn btn-info btn-sm" id="btn-success" style="background-color: #D1B147;"> View</button> </a></div>
I need click the submit button to reload table data,
But in javascript function , I don't known how to call the url pass parameters in thymeleaf.
I call this web page is below:
.....[menu partial code]....
<a class="dropdown-item" th:href="#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}">user list</a>
.....
the query and content Page:
<form >
<div class="col-sm-3 my-1">
<label class="sr-only" for="inlineFormInputName">Name</label> <input
type="text" class="form-control" id="inlineFormInputName"
placeholder="user name">
</div>
<div class="col-auto my-1">
<button type="submit" class="btn btn-primary query-submit"
id="querySubmit">Submit</button>
</div>
</div>
</form>
.....
<div class="row mt-5" th:fragment="table_content">
<div class="col">
...
<table class="table table-responsive table-hover">
<tbody>
<tr th:each="users,iter : ${response.content}">
<th scope="row" th:text="${iter.index+1}"></th>
<td class="text-info text-center"
th:text="${users.name}"></td>
</tr>
</tbody>
</table>
</div>
</div>
.....
I don't know the syntax in thymeleaf , if I need pass the params and call api in the js function. If the url will write #{/registeredUserList(type=0,userId=id0001,page=0,size=10)} like menu path, how can I write the syntax in the js function at url.
thank you~
$(function() {
$('#querySubmit').click(querySubmitClickAction);
querySubmit.addEventListener('click', querySubmitClickAction);
function querySubmitClickAction(e) {
$.ajax({
url: url, // here , I don't know syntax, I can't use [#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}] the path in here . how can I write the syntax.
type: 'POST',
success: function (data) {
$(".table_content").html(data);
}
})
}
});
</script>
Use th:inline="javascript" and the /*[[#{/url/}]]*/ syntax:
<script th:inline="javascript">
$(function() {
$('#querySubmit').click(querySubmitClickAction);
querySubmit.addEventListener('click', querySubmitClickAction);
function querySubmitClickAction(e) {
$.ajax({
url: /*[[#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}]]*/ 'dummy',
type: 'POST',
success: function (data) {
$(".table_content").html(data);
}
})
}
});
</script>
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'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