i would like to disabled asp=action link after one click
i have a foreach loop to display my book in table in my view
my asp-action for add book in the cart is in the loop but i want to disabled just the book who already in the cart not all books
<a asp-action="AcheterLivre" asp-Controller="Achat" asp-route-id="#item.Isbn" id="disabled" onclick="return myFunction(this);"> Ajouter
i try something with jquery but its dont work well
i tried this
<script>
function myFunction() {
$("#disabled").one("click", function () {
alert("this book is already in the cart");
});
}
i have this function in my class
its verify if the books is in the cart maybe i should use it ?
public bool IsPresent(string isbn)
{
//rechercher si l'isbn correspond a un livre de la liste
AchatLivreViewModel livre = ListeElements.Find(element => element.Isbn == isbn);
if (livre != null)
{
return true;
}
else
{
return false;
}
}
Why not trying this simple approach:
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Isbn
</td>
<td>
#item.Titre
</td>
<td>
<label class="btn btn-primary" style="padding:0">Add to Cart</label>
</td>
<td>
<label class="btn btn-danger" style="padding:0">Remove From Cart</label>
</td>
</tr>
}
</tbody>
And in your javascript, if you don't want to use Ajax, you can manage your cart items all on client side using an array of objects, Let's name it CartItems:
var CartItems = [];
$('.ADD2CART').click(function () {
if ($(this).closest('tr').hasClass("ExistingInCart")) {
alert('Already in Cart !!');
}
else {
// add this item to the Cart through Ajax or
// local javascript object: e.g.:
CartItems.push({
ISBN: $(this).closest('tr').find('td:eq(0)').text().trim(),
Title: $(this).closest('tr').find('td:eq(1)').text().trim(),
});
$(this).closest('tr').addClass("ExistingInCart");
}
return false; //to prevent <a> from navigating to another address
});
$('.RemoveFromCART').click(function () {
$(this).closest('tr').removeClass("ExistingInCart");
var isbn = $(this).closest('tr').find('td:eq(0)').text().trim();
CartItems = CartItems.filter(x => x.ISBN !== isbn);
return false;
});
Once you need to submit or post the page, you have all the already selected books in CartItems array.
To add this javascript code to your view, choose one of the options:
Put this block at the bottom of your view and copy the above script inside the <script></script> tag:
#section scripts{
<script>
.... copy it here ...
</script>
}
copy the script code inside a newFile.js and add it to your view
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/newFile.js"></script>
You may decide to bundle this newFile.js
try this:
Ajouter
And your Javascript:
function foo(input) {
if ($(input).attr('yetClickable') === '1') {
$(input).attr('yetClickable', '0');
return true;
}
else {
// this false returning will counteract the effect of click event on the anchor tag
return false;
}
}
Once an Item is removed from the cart, again you need javascript to select that Item by its Id and change the yetClickable attribute back to 1 (in order to be clickable).
Note: This idea above (upon your scenario) works until the page is not reloaded. Otherwise, you need to handle ADD/Remove operations on the Cart through Ajax.
Hope this helps.
Related
I am always getting null value through checkbox in mvc. If the checkbox is checked or uncheck it contain null value only.
Here is my code,
View Page
#model IEnumerable<SchoolWebApplication.Models.EventMaster>
<table id="tblEvent" class="table" cellpadding="0" cellspacing="0">
<tr>
<th style="width:100px; display:none">Event Id</th>
<th style="width:150px">Event</th>
<th style="width:150px">Active</th>
</tr>
#if(Model != null)
{
foreach (SchoolWebApplication.Models.EventMaster eventMaster in Model)
{
<tr>
<td class="EventID" style="display:none">
<span>#eventMaster.EventID</span>
</td>
<td class="Event">
<span style="color:darkgreen">#eventMaster.Event</span>
<input type="text" value="#eventMaster.Event" style="display:none; color:darkgreen" />
</td>
<td class="IsActive">
<span style="color:darkgreen">#eventMaster.IsActive</span>
#if (#eventMaster.IsActive == true)
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" checked="checked" name="abc"/>
}
else
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" name="abc"/>
}
</td>
<td>
<a class="Edit" href="javascript:;">Edit</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</td>
</tr>
}
}
</table>
<script type="text/javascript">
function AppendRow(row, EventID, Event, IsActive) {
//Bind EventID.
$(".EventID", row).find("span").html(EventID);
//Bind Event.
$(".Event", row).find("span").html(Event);
$(".Event", row).find("input").val(Event);
//Bind IsActive.
$(".IsActive", row).find("span").html(IsActive);
$(".IsActive", row).find("input").val(IsActive);
$("#tblEvent").append(row);
};
//Edit event handler.
$("body").on("click", "#tblEvent .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
$(this).hide();
});
//Update event handler.
$("body").on("click", "#tblEvent .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
$(this).hide();
var event = {};
event.EventID = row.find(".EventID").find("span").html();
event.Event = row.find(".Event").find("span").html();
event.IsActive = row.find(".IsActive").find("span").html();
$.ajax({
type: "POST",
url: "/Event/Update",
data: JSON.stringify({ eventMaster: event }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.IsActive);
}
});
});
</script>
Controller
try
{
EventMaster updatedEvent = (from c in entities.eventMaster
where c.EventID == eventMaster.EventID
select c).FirstOrDefault();
updatedEvent.Event = eventMaster.Event;
updatedEvent.IsActive = eventMaster.IsActive;
entities.SaveChanges();
return new EmptyResult();
}
catch (Exception ex)
{
return View();
}
Now, in table there is a three field EventID, Event and Active. In active there is a checkbox containing at update time.
Now, the issue is coming that if the checkbox is check or not check it is containing null value only.
So thats why at the fetch time it showing uncheck only.
Thank You.
Asking for the .val of a checkbox will get you the contents (if any) of the value attribute on the input element - this will not change when the user checks the box.
To check if a checkbox is checked in jQuery you should use something like:
if (input.is(":checked")){}
At the moment, you're storing the current value of .IsActive in the span and the value of the checkbox, and then when the update method runs, just grabbing that same value and putting it into the span - resulting in not updating anything.
Looking further at your code though - you should confirm what your method is actually posting back to the server - looking at it you are passing raw HTML into some parameters on the object:
event.IsActive = row.find(".IsActive").find("span").html();
At best, event.IsActive will be the string "True" (or False), rather than an actual boolean that your model is expecting. You would be better off changing that line to something like:
event.IsActive = row.find(".IsActive").find("input").is(":checked");
And then confirm what is being sent to the server in the network tab of your browser.
I am new to ASP.NET MVC and not that great with Javascript/jQuery.
My end goal is to provide a Delete link to the user to delete a row from a table. I want to do it as a POST operation rather than a GET as this, as I understand, POST is best practice. I wanted to add a confirm dialog before deleting but I didn't want to use the ugly javascript confirm dialog box and I was having problems with the form submitting without waiting for the jQuery dialog box to be answered. So, I turned the submit button into a regular button and added an onclick event which calls a ConfirmDelete javascript method in which I display a custom jQuery confirmation dialog. If answered in the affirmative, I find the form by ID using the keys of the record that the user wants to delete (keys = vendor Id and Effective Date). Once ethe form is found, I use Javascript to submit the form.
-------------------
public static class DateTimeExtensions
{
public static long ToLong(this DateTime value)
{
return long.Parse(value.ToString("yyyyMMddHHmmss"));
}
}
---------------------------------------
#using (Html.BeginForm("Delete", "StateAssessment", new
{
vendorId = Model.VendorId,
effectiveDate = Model.EffectiveDate
},
FormMethod.Post,
new { #id = "Form_" + Model.VendorId + "_" + #Model.EffectiveDate.ToLong() }
))
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.VendorId)
</td>
<td>
#Html.DisplayFor(modelItem => Model.EffectiveDate)
</td>
<td>
#Html.DisplayFor(modelItem => Model.LastTimeStamp)
</td>
<td>
#Html.ActionLink("Edit", "Edit",
new
{
vendorId = Model.VendorId,
effectiveDate = Model.EffectiveDate
})
<input value="Delete" class="btn btn-link" onclick="#string.Format("ConfirmDelete('{0}','{1}')", Model.VendorId, Model.EffectiveDate.ToLong())" />
</td>
</tr>
}
<script type="text/javascript">
function ConfirmDelete(vendorId, effectiveDate) {
var $myDialog = $('<div></div>')
.html('Are you sure that you want to delete this State Assessment?')
.dialog({
modal: true,
autoOpen: false,
title: 'Delete Confirmation',
buttons: {
"OK": function () {
$(this).dialog("close");
var form = $("#Form_" + vendorId + "_" + effectiveDate);
form.submit();
return true;
},
"Cancel": function ()
{
$(this).dialog("close");
return false;
}
}
});
$myDialog.dialog('open');
}
</script>
As you see, the ID of the form is constructed of the literal "Form_" concatenated with the vendor ID and EffectiveDate keys, where the EffectievDate value was normalized into a value that could be used in an ID.
This all worked, but man, it looks ugly to me and very long winded, especially when I think how easy this could be done in WinForms in a no more than few lines of code. I am looking for a better way. I'm thinking this code has noob written all over it and I'd like to denoob it.
Im trying to do a preloader for a page
the index action controller:
myapp/FR/Index
public ActionResult Index(){
return View(db.SP_GetRegistrosFRByID(0).ToList());}
the view, there isnt a begin form because is a get request:
#foreach (var item in Model)
{
...etc...<tr>
<td>
#Html.DisplayFor(modelItem => item.CodIden)
</td>
<td>
#Html.DisplayFor(modelItem => item.Nombres)
</td> ...etc
As David says it's a broad and open-ended question and you can apply lot of approaches. You have not given details about how index gets called (form submit, button click ..)
First you need a div with the loader image in the view where you need the preloader to display.
<div id="loader" class="loader">
Working.. <img src="~/Images/loading_small.gif" />
</div>
and now the JS function that shows/hides the div with the loader image based on your data loading status.
function pageLoading(status) {
if (status == 'true') {
$("#loader").css('display', 'block');
}
else {
$("#loader").css('display', 'none');
}
}
Before making the AJAX request you can call pageLoading("true"); to start displaying the image and finally when the table data gets populated call pageLoading("false"); to hide the loading image. Something like
$.ajax({
url: 'your index method url',
success: function (partial) {
$('#results').html(partial);
pageLoading("false");
}
error: function () {
pageLoading("false");
}
});
I'm going to use a grid view. it contains a check box per row.
its for deleting row. for example when user checked some checkbooks and click on delete button checked rows have to delete.
Now How can I give checked rows ID's in my action ?
Do you have any ideas ?
Thanks.
OK. We assume that you want to retrieve a list of products and show them in a raw html grid.
First of all, arrange your view like this:
#model IEnumerable<MyPrj.Product>
// ... Other codes ...
<table id="tblGrid">
<tr>
<th>Delete</th>
<th>ProductName</th>
// ... Other Properties ...
</tr>
#foreach(var item in Model)
{
<tr id="tr#(item.ProductID)">
<td>
#Html.Raw("<input type='checkbox' id='chk#(item.ProductID)' onclick='chkChange(#chkID)' />");
</td>
<td>#item.ProductName</td>
// ... Other Properties ...
</tr>
}
</table>
<input type="button" id="btnDelete" value="Delete Selected Rows" onclick="performDelete()"/>
Now, you have your view and it will render the grid for you with the supplied model. Then, you need to add some javascript and jquery codes to perform the row deletion for you.
A function to handle checkbox clicks:
<script>
function chkChange(id) {
if ($(id).val() != 'false')
$(id).val('false');
else
$(id).val('true');
}
// ...
</script>
And finally, a function to handle delete button clicks:
function performDelete() {
var rows = $("input:checked");
rows.each(function () {
$(this).parent().parent().remove();
});
}
That's it! - you're done. The complete <script> blog is like the following:
<script>
function chkChange(id) {
if ($(id).val() != 'false')
$(id).val('false');
else
$(id).val('true');
}
function performDelete() {
var rows = $("input:checked");
rows.each(function () {
$(this).parent().parent().remove();
});
}
</script>
You could place the grid along with its checkboxes inside an HTML form and make the Delete button as submit button for this form. Then when the button is clicked, the form will be submitted and the values of the selected checkboxes will be sent to the controller action so that you could delete the corresponding records.
I have two buttons in my page "Select All" and "Deselect All". I need to select the all the rows when i click the select all button and save the list of id in my variable. When Click deselect ll button it should be deselect the all rows . How will we do that?
[HttpPost]
public ActionResult Action Name(pssing value)
{
DataTable dataTable = new DataTable();
// my code
var MyModel = new List<List<string>>();
foreach (var joblist in Jobs)
{
var sublist = new List<string>();
sublist.Add(checked.false);
sublist.Add(values));
sublist.Add(values));
....etc
baseModel.Add(sublist);
}
return new DataTableResult(return);
}
Html :
<table cellpadding="0" cellspacing="0" border="0" class="display" id="AssignJobsTable" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>ID</th>
etc ......
</tr>
</thead>
script:
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
When i click the select all check box it cant bind the value form the controller.
try this
$('table#tableId> tbody > tr').addClass('highlight');
$('table#tableId> tbody > tr').removeClass('highlight')addClass('noHeilight');
sample table
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Cell phone</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
</tr>
</table>
sample script:
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
you should set id attr for checkboxes and put row id in the id attr and use the below code for selecting and deselecting:
$(document).ready(function(){
$("#selectall").click(function () {
var isSelect;
if($(this).is(":checked")) {
isSelect=true;
}else{
isSelect=false;
}
$("table tr td input[type=checkbox]").each(function(){
if(isSelect) {
$(this).prop('checked', true);
SelectedItems+=$(this).val()+":";
}else{
$(this).prop('checked', false);
SelectedItems="";
}
$("#Result").html(SelectedItems);
});
});
});
This is my approach of keeping track of all the selected rows in a datatable.
http://www.datatables.net/release-datatables/examples/plug-ins/plugin_api.html
The idea is to check the current page that the user is on and select/deselect the rows that is currently being viewed. You would loop through the page's rows and store the selected row into an array for future reference.
With this approach you would limit the time it takes to select/deselect all rows in the table.
Only show whats needed base on the view that user is seeing.
No hang up because the table is too busy checking/unchecking each row.
//stored checked box list
var result = [];
var selectAll = false;
var table5 = $('#example5').dataTable({
'fnDrawCallback':function(oSettings){
var anNodes = this.oApi._fnGetTrNodes( oSettings );
var anDisplay = $('tbody tr', oSettings.nTable);
//write your logic for pagination
//example
/*
$('tbody tr td:first-child input[type=checkbox]').on('click', function(){
if($(this).is(':checked')){
if($.inArray(....) != -1){push result}
}else{
if($.inArray(....) != -1){splice result}
}
}
if(selectAll){
for(var i = 0; i < anDisplay.length; i++){
//check if it's in result array
//add to the array
}
}else{
for(var i = 0; i < anDisplay.length; i++){
//check if it's in result array
//delete from the array
}
}
*/
}
})
That would be your logic for keeping track of the checked row.