I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code
Related
<div class="media-bottom">
#Html.TextAreaFor(model => model.Message, new { #class = "ui form", #rows = "5", #maxlenght = "300", #placeholder = "Paylaşmak istedikleriniz" })
</div>
<br />
<div class="footer-logo">
<button class=" mini ui right labeled right floated icon button" id="Button_Click" onclick="javascript: Button_Click();">
<i class="right arrow icon"></i>
Paylas
</button>
<div class="container bootstrap snippets bootdey downlines">
<div class="row">
<div class="col-md-6 col-xs-12">
<section class="widget">
<div class="widget-body">
<div class="widget-top-overflow windget-padding-md clearfix bg-info text-white">
</div>
<div class="post-user mt-n-lg">
<span class="thumb-lg pull-left mr media-object">
<img class=" img-circle" src="https://bootdey.com/img/Content/user_3.jpg" alt="...">
</span>
<span class="thumb-lg pull-right mr star">
<img src="~/Content/img/star.png" />
</span>
<div class="Thanksicon">
</div>
<div class="namespace">
<h5 class="mt-sm fw-normal text-black txt post">
#Html.DisplayFor(model => model.FullName)
<br />
<small class="text-black text-light departmen post">#Html.DisplayFor(model => model.Departmen)</small>
</h5>
</div>
</div>
<br />
<br />
<div class="text-light fs-mini m" id="Label1">
<div id="label1">
<p class="article">
#Html.DisplayTextFor(model=>model.Message)
</p>
</div>
<div class="thanksnames">
<span class="thumb-xs avatar mr-sm">
<img class="img-circle thank" src="https://bootdey.com/img/Content/user_2.jpg" alt="...">
</span>
<div class="mt-sm fw-normal text-black " id="person"> <small class="text-black text-light">Rose Tyler</small></div>
</div>
<br />
<div class="img"></div>
<div class="fs-mini text-muted text-right"><time class="time-table-top"></time></div>
</div>
</div>
</section>
</div>
</div>
</div>
This is my javascript
$(function () {
$('#Button_Click').on('click', function () {
$.ajax({
type: "POST",
url: '#Url.Action("Share")',
data: {
fullname: $("#username").val(),
departmen: $("#departmen").val(),
textarea: $(".ui.form").val()
},
datatype: "json",
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
});
});
});
This is my controller httppost
[HttpPost]
private JsonResult Share(SocialMedia data,string id)
{
var employee = _employeeRepository.GetById(id);
ViewBag.IsOwner = id == Session.GetEmployeeNo();
if (Session["MediaList"] == null)
{
Session["MediaList"] = new List<SocialMedia>();
}
var fullname = data.FullName;
var departmen = data.Departmen;
var textarea = data.Message;
foreach (MediaList list in data.MediaLists)
{
list.FullName = fullname;
list.Departmen = departmen;
list.Message = textarea;
list.Date = DateTime.Now.ToLocalTime();
if(data.Photo!=null)
{
list.Photo = data.Photo;
string fileName = Path.GetFileNameWithoutExtension(list.Photo);
list.Photo = "~/Image/" + fileName;
string _path = Path.Combine(Server.MapPath("~/Image/"),fileName);
}
}
return Json(new { data = PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml") });
// return PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml",
//return Json(new { success = true, message = GlobalViewRes.CreatedSuccessfully }, JsonRequestBehavior.AllowGet);
}
When I write an article and press the button, I want the page to appear below without refreshing and I want it to be repeated. It should be with the whole design. But when I press the button, I made ajax, but my ajax does not work, where am I going wrong?
Sorry for my English:)
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
You handle the data named 'data'. Then you are trying use it like 'result'. What is result, where is it came from? Whatever, try this
$('.downlines').html(data)
I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.
I am using JS in a razor page to grab a dynamic ID from a col in a foreach.
In the past, I have used this and it worked fine. However, it seems that it is currently only grabbing the ID from the first col no matter which one I click.
Can someone please tell me if I am still doing this right? Or if I am missing something. Thank you.
View:
<div class="list-group container" id="JobRequestMonitorTable">
<div class="row list-group-item list-group-item-heading container divTableHeading" style="margin-bottom:0px;">
<div class="col-md-4"> Job Code </div>
<div class="col-md-4"> Description </div>
<div class="col-md-2"> Schedule </div>
<div class="col-md-1"> Running </div>
<div class="col-md-1"></div>
</div>
#if (!string.IsNullOrEmpty(ViewBag.ErrorMessage))
{
<div class="row list-group-item-danger">
<div class="col-md-1 text-center">#ViewBag.ErrorMessage</div>
</div>
}
#foreach (var item in Model.JobRequests)
{
<div class="row list-group-item container">
<div class="hidden" data-id="#item.JobRequestId" id="requestId">#item.JobRequestId</div>
<div class="col-md-4">#item.JobCode</div>
<div class="col-md-4">#item.Description</div>
<div class="col-md-2">#item.Schedule</div>
#if (#item.IsRunning == true)
{
<div class="col-md-1" style="margin-left:25px;"><span class="glyphicon glyphicon-ok"></span></div>
<div class="col-md-1"></div>
}
else
{
<div class="col-md-1"></div>
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn"></button>
</div>
}
</div>
}
</div>
JS:
$("button").click(function () {
var col = $('#requestId');
var jobRequestId = col.data('Id');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
Really the only important part to see in the JS is var col = $('#requestId');
var jobRequestId = col.data('Id');
But I suppose I will include the whole script just in case people ask.
Your loop is creating multiple #requestId and #paramModalBtn elements when id attributes have to be unique within the DOM. Change the logic to use common classes instead. Then you can traverse the DOM to find the elements related to the button which was clicked. Try this:
$("button").click(function() {
var $col = $(this).closest('.row').find('.requestId');
var jobRequestId = $col.data('id');
console.log(jobRequestId);
// AJAX request...
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<div class="row list-group-item container">
<div class="hidden requestId" data-id="foo-bar">Job #1</div>
<!-- other content... -->
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
</div>
</div>
<div class="row list-group-item container">
<div class="hidden requestId" data-id="lorem-ipsum">#Job #2</div>
<!-- other content... -->
<div class="col-md-1">
<button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
</div>
</div>
All of your items inside the loop are getting the same id attribute, it is hard-codded
id="requestId"
the jQuery selector $('#requestId') is getting back the first one, this is by design.
I would add a data-id to each button and select the relevant col with that id.
For example the button will get:
<button data-col-id="#item.JobRequestId" class="glyphicon glyphicon-list-alt btn btn-primary"></button>
And then, its easy to grab that info on click:
$("button").click(function () {
var jobRequestId = $(this).data('col-id');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
I like this solution as you are not depended on your HTML structure and hierarchy thus selectors won't break often.
Once you have a button for each item, you could also store the data into the button value attribute, which leads to a simple implementation in the JS:
$("button").click(function (e) {
var jobRequestId = $(e.target).val();
console.log(jobRequestId);
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var arr = results;
//loop through arr created from dictionary to grab key(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
var myKey = key;
}
}
var name = myKey;
var value = results[myKey];
$('#modalName').text(name);
$('#modalMessage').text(value);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="1">Job 1</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="2">Job 2</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="3">Job 3</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="4">Job 4</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="5">Job 5</button>
Obs.: value must be equal to #item.JobRequestId like so: <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="#item.JobRequestId">Job 5</button>
I have a modal form that save me on certain data information, work correctly, but I need to update a in my view with the response and doesn't work correctly and bring me a list without format and class css, like when an error occurs, the modal disappears and brings back a page without css with all the validates error, what I have wrong in my code or that I do to fix it?
My Partial View
#model ControlSystemData.Models.Tourist
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel-Update">Ingresar Turista</h4>
</div>
#using(#Html.BeginForm("Create","Tourist", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="modal-body" style="text-align:center; padding:10px;">
#if (!string.IsNullOrWhiteSpace(ViewBag.Error))
{
<div class="alert alert-danger alert-dismissable" id="danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#ViewBag.Error
</div>
}
<div class="panel-body">
<div class="form-group">
#Html.TextBoxFor(u => u.Name, new { #class = "form-control", #placeholder = "Nombre del Pasajero" })
#Html.ValidationMessageFor(u => u.Name)
</div>
#*More Data Here*#
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</fieldset>
}
My Modal Bootstrap
<!--Modal Tourist-->
<div class="modal fade" id="Modal-Tourist" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<p class="body">
</p>
</div>
</div>
</div>
<!--End Modal Tourist-->
My Controller
[HttpPost]
public ActionResult Create(Tourist collection)
{
if (ModelState.IsValid)
{
db.Tourist.Add(collection);
db.SaveChanges();
return RedirectToAction("IndexByEventsTourist", "Tourist", new { id = collection.id });
}
Response.StatusCode = 400;
return PartialView("Create", collection);
}
My Script
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#alert').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('#Modal-Tourist form').on('submit', function () {
if ($(this).valid()) {
$.ajax({
url: '#Url.Action("Create","Tourist")',
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(result);
},
error: function (err) {
writeError('body', 'Wrong Data');
}
});
}
return false;
});
function getRequest(url) {
jQuery.noConflict();
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').click(function () {
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
I need that the modal stay in your position with your errors or rendering my correctly with the update.
Thanks
Images
RedirectToAction
public ActionResult IndexByEventsTourist(int id)
{
ViewBag.id = id;
var eventsById = db.Events.Where(u => u.id == id).FirstOrDefault();
ViewBag.Events = eventsById;
var touristByEvent = db.Tourist.Where(u => u.id == id).Include(u => u.Events).ToList();
ViewBag.TouristByEvent = touristByEvent;
return PartialView("IndexByEvents", touristByEvent);
}
Parent page (Render Div with the Partial Render or Update from Modal)
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-plus"></i> Add
</div>
<div class="panel-body">
<div class="row">
<div id="msgErrorNewTourist"></div>
<div class="col-lg-12" id="eventsDetailsList">
#{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}
</div>
</div>
</div>
</div>
</div>
</div>
After many tries, I changed the <script></script> (my script it was very obsolete) and I modified the <script> of this answer for my intent of load content dynamically and Validate the form before Post, Many Thanks to Sthepen Muecke for provide me a solution and clarify my issues... Thank you so much.
New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 3
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('a.newTourist').click(function () {
var url = '#Url.Action("Create", "Tourist", new { id = #Model.id })';
$(jQuery.noConflict);
$('#ModalContent').load(url, function (html) {
var form = $("#Modal-Tourist form");
$.validator.unobtrusive.parse(form);
$("#Modal-Tourist").modal('show');
form.submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
var content = '#Url.Action("IndexByEventsTourist", "Tourist", new { id = #Model.id })';
$('#eventsDetailsList').load(content);
}
});
return false;
});
});
});
});
</script>
i have a problem when implementing pagedlist mvc in my website project. I used pagedlist mvc to show partial view. When button previous is click, the parameter doesn't complete pass, just the page number that pass and the other is null. This is my controller
public ActionResult StoreItemView(string jenis, string sorting_key, int? Page_No)
for previous button it will create link like this
localhost:20208/StoreItem/StoreItemView?Page_No=1
and has different with next button,that create link that contain all parameter
localhost:20208/StoreItem/StoreItemView?jenis=&sorting_key=&Page_No=2
why it's different call for previous and next button ?
i create the pager like this in cshtml
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action(
"StoreItemView",
new
{
jenis = ViewBag.jenis,
sorting_key = ViewBag.sorting_key,
Page_No = page
}
),
PagedListRenderOptions.PageNumbersOnly
)
</div>
and i use javascript too for load partial view , my javascript is
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});
</script>
I stuck in this problem almost 2 days. I hope the people who are here can help me. Thank you before :)
----EDIT------
#model PagedList.IPagedList<MVC_EDOLPUZ.Models.StoreItemModel>
#using System.Globalization
#using PagedList.Mvc
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
<h3><span class="label label-primary">DOLANAN PUZZLE ITEM</span></h3>
<select id="Sorting_Order" name="Sorting" onchange="reloadPartialDDL()">
<option value="0">-Urutkan Berdasarkan-</option>
<option value="nama">Nama</option>
<option value="rendah">Harga Terendah</option>
<option value="tinggi">Harga Tertinggi</option>
</select>
<div id="products" class="row list-group">
#foreach (var item in Model)
{
<div class="item col-xs-5 col-lg-3">
<div class="thumbnail">
<img class="group list-group-image img-responsive" src="#Url.Content(#item.gambar_barang)" alt="" />
<div class="caption">
<h4 class="group inner list-group-item-heading">
#item.nama_barang
</h4>
<p class="group inner list-group-item-text">
<span class="label label-warning">#item.deksripsi_barang</span>
</p>
<div class="row">
<div class="col-xs-1 col-md-6">
<input id="#item.nama_barang" type="number" class="rating" min="1" max="5" step="0.5" data-size="xs" value="#item.rating_barang">
</div>
<script>
$('##item.nama_barang').rating('refresh', { disabled: true, showClear: false, showCaption: false });
</script>
</div>
<div class="row">
<div class="col-lg-5 col-xs-4">
<p class="lead" style="font-weight: bolder; color: red;">
#string.Format(new CultureInfo("id-ID"), "{0:C}", #item.harga_barang)
</p>
</div>
<div class="col-lg-1 col-xs-2">
<a class="btn btn-success btn-responsive btn-xs" onclick="addItemToCart('#item.id_barang')" href="#">Add to cart</a>
</div>
</div>
</div>
</div>
</div>
}
</div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#*#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))*#
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action(
"StoreItemView",
new
{
jenis = ViewBag.jenis,
sorting_key = ViewBag.sorting_key,
Page_No = page
}
),
PagedListRenderOptions.PageNumbersOnly
)
</div>
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});
</script>
that's my code for the view, and this controller that handle it's view
[HttpGet]
public ActionResult StoreItemView(string jenis, string sorting_key, int? Page_No)
{
ViewBag.jenis = jenis;
ViewBag.sorting_key = sorting_key;
List<StoreItemModel> products = StoreItemRepository.getItemList(jenis, sorting_key);
foreach (var items in products)
{
items.rating_barang = StoreItemRepository.getRatingBarang(items.id_barang);
}
int Size_Of_Page = 4;
int No_Of_Page = (Page_No ?? 1);
PagedList.PagedList<StoreItemModel> show = new PagedList.PagedList<StoreItemModel>(products, No_Of_Page, Size_Of_Page);
return PartialView("_StoreItem", show);
}
Please use like below
<div id="myPager" location="Url.Action("StoreItemView", new {jenis = ViewBag.jenis, sorting_key = ViewBag.sorting_key, Page_No = page})">
#Html.PagedListPager(
Model,
page => Url.Action("StoreItemView"),
PagedListRenderOptions.PageNumbersOnly
)
and javascript must be like
Before using the please check ViewBag.sorting_key and ViewBag.jenis is holding any value using alert in javascript. and I am not qable to see any tag with id="container_item_store". Make sure the container_item_store id must be place in some where in your view.
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
var location = $(this).attr('location');
$.ajax({
url: location,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});