I have the following code to update my Cart items Quantity:
<div class="cart-col cart-col-qty" data-caption="Quantity">
<div id="item-count-#item.item_id">
#Html.TextBoxFor(model => model.CartItems[ix].Count,
new
{
#class = "test11 form-control",
#type = "text",
#min = "0"
})
<a href="#" class="RefreshQuantity tessss btn btn-danger btn-to-danger btn-sm btn-icon" data-id="#item.item_id"
txt-id="CartItems_#(ix)__Count"><i class="fa fa-2x">+</i></a>
</div>
I am using ajax to make a post request upon clicking the anchor element with this code:
$(".RefreshQuantity").click(function () {
// Get the id from the link
var recordToUpdate = $(this).attr("data-id");
var countToUpdate = $("#" + $(this).attr("txt-id")).val();
if (recordToUpdate != '') {
// Perform the ajax post
$.post("/ShoppingCart/UpdateCartCount", { "id": recordToUpdate, "cartCount": countToUpdate },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
}
location.reload();
});
}
});
I want to remove the click function on the anchor and use the input's onKeyUp event to make the ajax request with the cartItem id and the quantity without page refresh. How can I achieve this?
You can use this instead of .click
$("#YourElement").on('keyup', function (e) {
e.preventDefault(); //This will avoid post form
if (e.keyCode === 13) { //This evaluates enter key
//Your logic
}
});
Related
I've just implemented search in a sample web app that I'm working on. Search works fine and here is how I've done that:
Typecript Search function
private search(keyword) {
try {
if (keyword === '' || keyword === undefined) {
$('employees_list tbody').empty();
} else { const data = { keyword: keyword };
Util.request(this.urlSearchEmployee, 'GET', 'html', (response) => {
const currentKeyWord = $('#keyword').val();
if (currentKeyWord === keyword) {
$('#employees_list tbody').empty();
$('#employees_list tbody').append(response);
}
}, function () {
$.notify('Failed to get data. Please try again.');
console.error('Failed to get data #T09576. Please try again.');
}, data);
}
} catch (e) {
console.error(e);
}
}
Search function in controller
var employees = await _db.Employees.Where(e =>
e.LastName.ToLower().Contains(keyword.ToLower()) ||
e.FirstName.ToLower().Contains(keyword.ToLower()) ||
e.Position.ToLower().Contains(keyword.ToLower())
).ToListAsync();
//Console.WriteLine(employees);
ViewData["EmployeesList"] = employees;
return PartialView("~/Views/Employee/_TableData.cshtml");
Table View file
#{
List<Employee> EmployeeList = (List<Employee>)ViewData["EmployeesList"];
}
#if (EmployeeList.Count > 0)
{
foreach (var employee in EmployeeList)
{
<tr class="employees-row" style="width: 20%; text-align:center;">
<td>#employee.FirstName</td>
<td>#employee.LastName</td>
<td>#employee.Position</td>
<td>#employee.Department</td>
<td>#employee.Salary</td>
<td>#employee.DateJoined</td>
<td>#employee.LastUpdated</td>
<td>
<button type="button" class="btn btn-sm btn-dark employee-edit" data-id="#employee.EmployeeId">
<i class="fa fa-edit"></i>
</button>
<button type="button" class="btn btn-sm btn-danger employee-delete" data-id="#employee.EmployeeId">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
}
}
The search works fine. But when the search result is loaded there are two buttons to edit or delete. And when I click these buttons they don't do anything. The same buttons work when the table rows are normal meaning when table rows are not search results.
UpdateHere is the delete button click events:
Typescript:
$('.employee-delete').click((e) => {
alert("Delete Button Clicked");
const id = $(e.currentTarget).data('id');
const data = {
id: id
};
this.delete(data);
});
Then the delete() method in typscript:
private delete(data) {
try {
if (confirm("Are you sure you want to delete this employee?") == true) {
Util.request(this.urlDeleteEmployee, 'post', 'json', () => {
$.notify(`Employee deleted successfully.`);
location.reload();
}, () => {
$.notify(`Failed to delete Employee. Please try again`);
}, data);
}
} catch (e) {
console.error(e);
}
}
This after search result the delete button nor edit button doesn't work.
Your issue seems to be when you search the table, it will rebinding the DOM. So your previous click bindings of buttons will be vanished.
So rather than using $('.employee-delete').click(...) use delegate type bindings with $(document).on("click", ".employee-delete", (e) => { ... }.
It will assigned to dynamically created objects also. Update it like below.
$(document).on("click", ".employee-delete", (e) => {
const id = $(e.currentTarget).data('id');
const data = { id: id };
this.delete(data);
});
So far, this will add only the first item to the cart and stay on the same page. Each page has at least 3 items which it creates a new form with each time. The other products it wont add to the cart and it redirects me to the Home Index View. I am using Ajax to submit the form. The error message (only when adding the first item to the cart) pops up instead of the success message, so something is not going through right. This is what I have so far.....
View:
#foreach (var item in Model)
{
<a href="#Url.Action("Details","Products", new { id = item.ProductID
})" class="btn btn-outline-secondary">View details</a>
<div id="MessageContent"></div>
#using (Html.BeginForm
("", "", FormMethod.Post, new { #productID = item.ProductID, Id = "myForm" }))
{
#Html.HiddenFor(x => x.Where(p => p.ProductID ==
item.ProductID).FirstOrDefault().ProductID)
<input type="submit" onclick="addToCart(1)" value="Add To Cart"
class="btn btn-primary" />
}
}
Ajax (on view):
<script type="text/javascript">
$('#myForm').submit(function (e) {
e.preventDefault();
$('#MessageContent')
.html("<div class='alert alert-info'> Adding to cart...</div>")
$.ajax({
url: '#Url.Action("AddToCart", "Home")',
type: 'POST',
data: $(this).serialize(),
success: function (e) {
$('#MessageContent')
.html("<div class='alert alert-success'>Item added to cart</div>");
},
error: function (e) {
$('#MessageContent').html("<div class='alert alert-warning'>Oops...Some error Occured.</div>");
}
});
});
</script>
Controller:
[HttpPost]
public void AddToCart(int productID)
{
////Create the Shell Local Shopping Cart
Dictionary<int, ShoppingCartViewModel> shoppingCart = null;
//Check the global shopping cart
if (Session["cart"] != null)
{
//if it has stuff in it, reassign to the local
shoppingCart = (Dictionary<int, ShoppingCartViewModel>)Session["cart"];
}
else
{
//create an empty Local Version
shoppingCart = new Dictionary<int, ShoppingCartViewModel>();
}
//get the product being displayed in the view
Product product = db.Products.Where(x => x.ProductID == productID).FirstOrDefault();
if (product == null)
{
//return RedirectToAction("Index");
}
else
{
//title is valid
ShoppingCartViewModel item = new ShoppingCartViewModel(1, product);
//if the item is already in the cart just increase the qty
if (shoppingCart.ContainsKey(product.ProductID))
{
shoppingCart[product.ProductID].Qty += 1;
}
else //add the item to the cart
{
shoppingCart.Add(product.ProductID, item);
}
//now that the item has been added to the local cart,
//update the session cart with the new item/qty
Session["cart"] = shoppingCart;
}
}
UPDATE: I just fixed the error Message by deleting the datatype: 'json' from the ajax function.
I have it figured out. Rookie Mistake... I was using a unique '#myform' id on each form so it was no longer being used after the first form was submitted. The MessageContent id, however, I could not get to pop up without displaying on all the form or only one. That's not important though as I can just remove that portion.
Hello I am trying to pass the parameter id to the a JsonResult. Currently the code below works if I hard code my id and when I do not pass a parameter through.
The code below is for the Events Calendar View
<script>
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: "prev,next,today",
center:'title',
right:''
// right: 'month'
},
defaultView: 'month',
editable:false,
allDaySlot: false,
selectable: true,
slotMinutes: 15,
firstDay:1,
events: 'GetEvents/'
});
});
</script>
<div id='calendar' style="width:90%">
</div>
JsonResult where the id is currently hard coded I would like to pass this value through when I click the button to load the page e.g. /EventsCalendar/2
public JsonResult GetEvents(string start , string end)
{
int id = 1;
var events = CustomEvents(start , end, id );
return Json(rows, JsonRequestBehavior.AllowGet);
}
Item 2 is the name of the button and Item 1 is the name
#Html.ActionLink(item.Item2, "ShowEvents", new { controller = "Leaves", id = item.Item1 }, new { #Class = "btn btn-primary" })
public ActionResult EventsCalendar()
{
return View();
}
I have a dropdownlist:
<div class="a">
#Html.DropDownList("StorageId", null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StorageId)
</div>
Html:
<div class="a">
<select class="form-control" id="StorageId" name="StorageId"><option selected="selected" value="1">Brak Brak</option>
<option value="2">First</option>
<option value="23">Second</option>
<option value="24">Third</option>
</select>
<span class="field-validation-valid" data-valmsg-for="StorageId" data-valmsg-replace="true"></span>
</div>
populated with code:
ViewBag.StorageId = new SelectList(unitOfWork.storageRepository.Get(), "Id", "Name", deviceusage.StorageId);
all data is send to controller with this Ajax request:
$.ajax({
url: "/DeviceUsage/Edit",
type: "POST",
contentType: "application/json; charset=utf-8",
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
},
data: JSON.stringify({
deviceusage: {
DeviceInstanceId: $('.a').children("#DeviceInstanceId").val(),
UserId: $('.a').children('#UserId').val(),
StorageId: $('.a').children('#storageId').val()
}
}),
error: function (data) {
alert("wystąpił nieokreślony błąd " + data);
},
success: function (data) {
if (data.ok) {
$("#Modal").modal('hide');
window.location = data.newurl;
}
else {
$('.modal-body').html(data);
}
}
})
No Matter what I select in this dropdown it's not updated. After changing first selection always first one is send to controller.
#Update:
Here is a controller method I use for handling 'Post` calls:
public ActionResult Edit([Bind(Include="StorageId,UserId,DeviceInstanceId")] DeviceUsage deviceusage)
{
ValidateRequestHeader(Request);
if (deviceusage.UserId == 6 && deviceusage.StorageId == (int)Storage.Biurko)
{
ModelState.AddModelError("", "Zarezerwowane urządzenie nie moze byc przypisane do biurka");
}
if (deviceusage.UserId == 1 && deviceusage.StorageId == (int)Storage.Biurko)
{
ModelState.AddModelError("", "Wolne urządzenie nie może przebywać na jakimś biurku");
}
if ((deviceusage.UserId != 1 & deviceusage.UserId != 6) & deviceusage.StorageId != (int)Storage.Biurko)
{
ModelState.AddModelError("", "Urzązenie przypisane do kogos nie moze przebywac w magazynie");
}
if (ModelState.IsValid)
{
unitOfWork.deviceUsageRepository.Update(deviceusage);
unitOfWork.Save();
return Json(new { ok = true, newurl = Url.Action("Index") });
}
ViewBag.DeviceInstanceId = new SelectList(unitOfWork.deviceInstanceRepository.Get(), "Id", "SerialNo", deviceusage.DeviceInstanceId);
ViewBag.StorageId = new SelectList(unitOfWork.storageRepository.Get(), "Id", "Name", deviceusage.StorageId);
var data = unitOfWork.userRepository.Get()
.Select(s => new
{
Id = s.Id,
Credentials = s.Name + " " + s.Surname
}
);
ViewBag.UserId = new SelectList(data, "Id", "Credentials", deviceusage.UserId);
return PartialView(deviceusage);
}
As you can see its returning a PartialView because dropdown is in modal windows which is updated with a return of Ajax call.
#Update2
During test using browser console with this code:
$('#StorageId').val()
I managed to find that:
its correctly returning values before first send
if the modal is reloaded because of that the data was wrong. Changing selected value using list does not change anything. The value returned with this code is falue send with ajax.
The reason behind the issue that always first value is getting submitted to controller is because of this attr which is set to first option in your dropdown list box,selected="selected".
You could bypass this behaviour with change event call back like this
JQUERY CODE:
$('.a select').on('change',function() {
$(this).find('option:selected').attr("selected","selected");
});
Add the above event listener inside the $(document).ready( function() { ...... }) or onload of the body of your page.
Happy Coding :)
Try:
StorageId: $('.a').children('#StorageId').val()
note uppercase 'S' on #StorageId
Also you could probably just do:
StorageId: $('#StorageId :selected').val();
I've created a jsfiddle to demonstrate: http://jsfiddle.net/2qpBZ/
I need to create the confirm box in mvc controller?. Using this 'yes' or 'no' value I need to perform the action in my controller. How we do that?
Sample code:
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true)
{ true code}
else { else code}
}
You can do this with ActionLink
#Html.ActionLink(
"Delete",
"DeleteAction",
"Product",
new { confirm = true, other_parameter = "some_more_parameter" },
new { onclick = "return confirm('Do you really want to delete this product?')" })
If user confirm, then link parameter will pass to the controller action method.
public ActionResult DeleteAction(bool confirm, string other_parameter)
{
// if user confirm to delete then this action will fire
// and you can pass true value. If not, then it is already not confirmed.
return View();
}
Update
You can not show message box in controller side. But you can do this like following
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true){ ViewBag.Status = true }
else { ViewBag.Status = false}
return View();
}
And view
<script type="text/javascript">
function() {
var status = '#ViewBag.Status';
if (status) {
alert("success");
} else {
alert("error");
}
}
</script>
But these all codes are not elegant way. This is solution of your scenerio.
Yes, you can do this with #Html.ActionLink as AliRıza Adıyahşi has commented.
Subscribe to the onclick event of the #Html.ActionLink
Here is the implementation:
#Html.ActionLink("Click here","ActionName","ControllerName",new { #onclick="return Submit();"})
And in javascript write the confirm box.
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
return true;
} else {
return false;
}
}
</script>
Edit
Try like this:
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
document.getElementById('anchortag').href += "?isTrue=true";
} else {
document.getElementById('anchortag').href += "?isTrue=false";
}
return true;
}
</script>
#Html.ActionLink("Submit", "Somemethod", "Home", new { #onclick = "return Submit();", id = "anchortag" })
Now in your controller do some operations based on the isTrue querystring
public ActionResult Somemethod(bool isTrue)
{
if (isTrue)
{
//do something
}
else
{
//do something
}
return View();
}
You dont create confirm box in a Controller, but yes in a View, using JQuery Dialog.
The Controller is already inside the server, so you don't have user interactions there.
Your View, in the other hand, is the place where the user will choose options, type information, click on buttons etc...
You can intercept the button click, to show that dialog, and only submit the post when the option "Yes" gets clicked.
JQuery Dialog requires jquery.js, jquery-ui.js, jquery.ui.dialog.js scripts referenced in your page.
Example:
$(function(){
$("#buttonID").click(function(event) {
event.preventDefault();
$('<div title="Confirm Box"></div>').dialog({
open: function (event, ui) {
$(this).html("Yes or No question?");
},
close: function () {
$(this).remove();
},
resizable: false,
height: 140,
modal: true,
buttons: {
'Yes': function () {
$(this).dialog('close');
$.post('url/theValueYouWantToPass');
},
'No': function () {
$(this).dialog('close');
$.post('url/theOtherValueYouWantToPAss');
}
}
});
});
});
I can confirm that AliRıza Adıyahşi's solution works well.
You can also customize the the message. In my case we're using MVC and Razor, so I could do this:
<td>
#Html.ActionLink("Delete",
"DeleteTag", new { id = t.IDTag },
new { onclick = "return confirm('Do you really want to delete the tag " + #t.Tag + "?')" })
</td>
Which showed a dialog with a specific record named in it. Might also be possible to give the confirm dialog a title, haven't tried that yet.
<a href="#Url.Action("DeleteBlog", new {id = #post.PostId})" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">
<i class="glyphicon glyphicon-remove"></i> Delete