I have CheckBox which is working like Toggle Switches and by default it is set Checked/ON and when i UnChecked/OFF the CheckBox,it will pass the value (OFF) not problem , but when i Checked the Checkbox again it cant pass the value (ON).
Can anyone please help me or point me in the right direction!
Thanks in advance :)
Example With ScreenShots:
By Default it is set Checked/ON
Now I UnChecked/OFF , its pass the Value
Now i Checked/ON again, it cant pass the Value
View:
<tbody>
#foreach (var rma in Model)
{
<tr>
<td>
<label class="switch switch-text switch-primary switch-pill">
<input type="checkbox" class="switch-input" checked>
<span data-on="ON" data-off="OFF" class="switch-label"></span>
<span data-id="#rma.Id" class="switch-handle"></span>
</label>
</td>
</tr>
}
</tbody>
JavaScript:
<script>
$(document).ready(function () {
$('.switch-handle').click(function () {
var Id = $(this).data('id');
var checkStatus = this.checked ? 'ON' : 'OFF';
$.ajax({
type: "POST",
url: '#Url.Action("UpdateNtf", "Account")',
data: {
id: Id,
status: checkStatus
},
dataType: 'json',
success: function (result) {
if (result) {
console.log("Ok");
} else {
console.log("error");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
})
});
});
</script>
Controller:
public JsonResult UpdateNtf(int? id, string status)
{
var result = db.RMA_History.Where(a => a.Id == id).FirstOrDefault();
if (result != null)
{
result.NTFOnOFF = status;
db.SaveChanges();
}
return Json(result,JsonRequestBehavior.AllowGet);
}
Related
Can you help me on how to get the checkbox values to be a data array? I code like this, and don't get any output. Thanks for helping me.
In my html :
<input class="form-check-input delete-checkbox" type="checkbox" name="checkbox[]" id="checkbox" value="{{ $item->id }}"data-id="{{ $item->id }}">
In my JS:
function multiple_delete(id) {
const selected = [];
$(".form-check input[type=checkbox]:checked").each(function () {
selected.push(this.value);
});
if (selected.length > 0) {
dataid = selected.join(",");
$.ajax({
url: "multiple-delete",
type: "POST",
data: +dataid,
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
My output :
First, you are using the wrong selector. You should change .form-check in the javascript to .form-check-input or .delete-checkbox. Also you can easily get values of the selected checkboxes using jquery's .map() method.
Change your javascript code to something like this
function multiple_delete(id) {
const selected = $(".delete-checkbox:checked").map((i, el) => el.value).get();
if (selected.length > 0) {
$.ajax({
url: "multiple-delete",
type: "POST",
data: selected.join(","),
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
This is my code in Razor view that basically displays the table by extracting information from database -
#model List<EmpoyeeInfo.Models.FFX_HR_Employees>
#using System.Reflection;
#{
ViewBag.Title = "Employee Information";
var Properties = Model[0].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
string[] head = new string[Properties.Count()];
}
<div id="web-top">
<div id="horizontal-line"></div>
<input class="search-box-text" type="text" spellcheck="false" placeholder="Search Individual Record..." title="Search Individual Record" id="searchbox" name="searchbox" />
</div>
<div id="web-main">
<table class="employee-info">
<tr>
#foreach (var Property in Properties)
{
if (Property.Name.Equals("AnnualHolidayEntitlement"))
{
<th colspan="2">#Property.Name</th>
}
else
{
<th>#Property.Name</th>
}
}
</tr>
#foreach(var Row in Model)
{
<tr>
#{
Type type = Row.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
}
#foreach (PropertyInfo prop in props)
{
if (prop.Name.Equals("AnnualHolidayEntitlement"))
{
<td contenteditable="true">#prop.GetValue(Row, null)</td>
}
else
{
<td>#prop.GetValue(Row, null)</td>
}
}
<td class="saveToDB">SAVE</td>
</tr>
}
</table>
</div>
but as i type in the search box text, an ajax calls are made -
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (result) {
//do stuff;
},
error: function () {
console.log("no display");
}
});
}
now how do i reload the div - "web-main" and update the Model value such that as the user searches for a name, the table also needs to be updated.
Code below will append the results to the div 'web-main'. You need to manipulate the success portion of jQuery in your code
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (data) {
//do stuff;
console.log(data);
$("web-main").append(JSON.stringify(data));
},
error: function () {
console.log("no display");
}
});
}
Hi I am working in one application and in that I am using json call to decline the request.
Now when I am going to decline request one by one I find one issue that on single page when I am decline one request it get declined but when I am going to decline 2nd request it is not declining that request.
In case if I need to decline 2nd request in that case 1st I need to refresh that page and then after I am able to decline that 2nd request.
Below is the screen shot
My view page code.
In script tag
function declinestudentrequest() {
var StudentRequestId = document.getElementById('hdstatusstudentrequestid').value;
var StatusId = document.getElementById('hdstatusdecline').value;
$.ajax({
url: '/Account/declinestudentrequest',
type: 'GET', // You can use GET
data: { 'StudentRequestId': StudentRequestId },
dataType: "json",
context: this,
cache: false,
success: function (data) {
if (data == "Success") {
$("#GetStatusMessage_" + StudentRequestId).css({ "display": "block" });
$('#div_p_' + StudentRequestId).text("You have decline for student Response");
$("#GetReqdec_" + StudentRequestId).hide();
}
else { alert('Some Error'); }
},
error: function (request) {
console.log(request);
}
});
}
Design
#if (Convert.ToInt16(item.StatusId) == 1)
{
<div id="GetStatusMessage_#item.StudentRequestId" style="display:none;">
<p id="div_p_#item.StudentRequestId">Waiting for student Response.</p>
</div>
<div id="GetReqdec_#item.StudentRequestId">
#using (Html.BeginForm("TutorDashboard", "AccountController"))
{
#Html.TextAreaFor(model => item.Description, new { #class = "form-control", #placeholder = "Please describe how you can help.", #id = "txtdescription" })
<br />
<span>Hourly rate :</span>
#Html.EditorFor(model => item.Ratedummy, new
{
htmlAttributes = new { #class = "form-control", placeholder = "Price", maxlength = 10, id = "txtrate" }
})
<p class="text-right">
<input type="hidden" id="hdstatusrequest" name="hdstatusrequest" value='2' />
<input type="hidden" id="hdstatusdecline" name="hdstatusdecline" value='3' />
<input type="hidden" id="hdstatusstudentrequestid" name="hdstatusstudentrequestid" value='#item.StudentRequestId' />
<input type="button" onclick="return declinestudentrequest();" class="btn btn-default btn-hire decline_btn" value="Decline" />
</p>
}
</div>
}
My Account controller Side code
public ActionResult declinestudentrequest(string StudentRequestId)
{
string result = "";
try
{
if (User.Identity.IsAuthenticated)
{
TutorStudentRequest tsr = new TutorStudentRequest();
tsr.StudentRequestId = Convert.ToInt32(StudentRequestId);
tsr.Rate = 0;
tsr.StatusId = 3;
db.TutorStudentRequests.Add(tsr);
db.SaveChanges();
result = "Success";
}
else
{
return RedirectToAction("Index", "Home");
}
}
catch (Exception ex)
{
result = "Error";
throw ex;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
Why my second request for decline is not working ?
The issue is resolved as there was an issue of id getting conflicting so I have tried some thing like.
On view page I made changes as
<input type="hidden" id="hdstatusstudentrequestid_#item.StudentRequestId" name="hdstatusstudentrequestid" value='#item.StudentRequestId' />
<input type="button" onclick="return declinestudentrequest('#item.StudentRequestId');" class="btn btn-default btn-hire decline_btn" value="Decline" />
and in script
function declinestudentrequest(id) {
var StudentRequestId = document.getElementById('hdstatusstudentrequestid_'+id).value;
var StatusId = document.getElementById('hdstatusdecline').value;
$.ajax({
url: '/Account/declinestudentrequest',
type: 'GET', // You can use GET
data: { 'StudentRequestId': StudentRequestId },
dataType: "json",
context: this,
cache: false,
success: function (data) {
if (data == "Success") {
$("#GetStatusMessage_" + StudentRequestId).css({ "display": "block" });
$('#div_p_' + StudentRequestId).text("You have decline for student Response");
$("#GetReqdec_" + StudentRequestId).hide();
}
else { alert('Some Error'); }
},
error: function (request) {
console.log(request);
}
});
}
Here I am making uniqueness from while passing studentrequestid as unique
// this is my kendo strip code......
#(Html.Kendo().TabStrip()
.Name("TabStripPatientHome")
.Items(tabStrip =>
{
tabStrip.Add()
.Text("Patient Home")
.Content(#<text>
<table >
<tr>
<td>
Last Order/Consult
<br />
#LastOrderConsultData()
</td>
</tr>
</table>
</text>);
tabStrip.Add()
.Text("History")
.Content(#<text>
<p style="font-size: large; color: Navy;">
Order/Consult History
</p>
#RenderOrderHistory()
<br />
<p style="font-size: large; color: Navy;">
Consult Pre-Purchase History
</p>
#RenderTeleconsultHistory()
</text>);
}
})
// define the kendo event
.SelectedIndex(0)
.Events(events => events
// triggering select event in Kendo UI TabStrip. .Select("onSelectTab")
.ContentLoad("onLoadTab"))
)
// triggering the select and content load event using ajax call.....
function onSelectTab(eventItem) {
debugger;
setTimeout("saveTabIndexSession();", 1000);
}
function onLoadTab(eventItem) {
debugger;
setSelectedTabIndex();
}
function setSelectedTabIndex() {
debugger;
var tabStrip = $("#TabStripPatientHome").data("tTabStrip");
var tabIndex = getPatientTabIndex();
//alert(tabIndex);
tabStrip.select($(".t-item", tabStrip.element)[tabIndex]);
}
function getPatientTabIndex() {
debugger;
var returnVal = 0;
$.ajax({
url: '#Url.Action("GetTabIndexFromSession", "Operations")',
type: 'POST',
success: function (data) {
returnVal = parseInt(data);
},
async: false,
error: function (xhr) {
alert("Something went wrong while checking Order Details, please try again");
}
});
return returnVal;
}
function saveTabIndexSession() {
debugger;
var tabStrip = $("#TabStripPatientHome").data("tTabStrip");
var tabIndex = tabStrip.getSelectedTabIndex();
$.ajax({
url: '#Url.Action("SaveTabIndexSession", "Operations")',
type: 'POST',
data: { selectedTabIndex: tabIndex },
success: function (data) {
},
async: false,
error: function (xhr) {
alert("Something went wrong while checking Order Details, please try again");
}
});
//return _IsRXProductOrder;
}
// when i am clicking on another kendotab it append the url like #TabStripPatientHome-2
// http://operations.mdalignelocal.com/Operations/PatientHome?Patientid=837545#TabStripPatientHome-2
Basically what I want to do is:
Click on a button to delete a record.
Delete the record if a specific column (Location) is null (this is done and works fine)
Delete the record, BUT if the specific column is not null, ask the user to confirm.
So step 3 is the tricky part. With the AJAX, I call the deleteChannel(url) that you see below, which calls the proper method in code-behind. Now here is the tricky part:
if (channel != null && channel.Location != null)
{
// How do I do this? (Notice that this is code-behind)
ShowDialogThatAsksUserToConfirm()
}
The code: ShowDialogThatAsksUserToConfirm() needs to call back to the client saying that "The Location column is not null", and wait for user to say delete anyway, or cancel.
I have this code that will call a method in code behind:
function deleteChannel(url) {
$.ajax({
url: url,
type: "POST",
cache: false,
contentType: 'application/html; charset=utf-8',
data: $("form").serialize(),
dataType: 'html',
success: function (msg) {
showDialog('successDiv');
},
error: function (msg) {
alert("error");
showDialog('errorDiv');
}
});
}
And the showDialog(...) looks like this:
function showDialog(divID) {
$("#" + divID).dialog({
show: "clip",
hide: "clip",
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
}
The code-behind looks like this:
[HttpPost]
public ActionResult DeleteChannel(int id)
{
var statusCode = new HttpStatusCode();
using (var context = new MaaneGrisContext())
{
var channel = context.Channels.FirstOrDefault(x => x.ID == id);
if (channel != null && channel.Location != null)
{
if (Confirmation()) //The Confirmation() method not implemented yet, but it should ask user to confirm
{
context.Channels.Remove(channel);
context.SaveChanges();
List<ChannelModel> updatedChannelList = new List<ChannelModel>();
context.Channels.AddRange(context.Channels);
return View("ChannelDetails", updatedChannelList);
}
}
}
Here is the View:
<table style="border: ridge 1px">
<tr>
<th>Name</th>
...
</tr>
#{
foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(m => item.ChannelName)</td>
<td>#Html.DisplayFor(m => item.Description)</td>
<td>#Html.DisplayFor(m => item.Unit)</td>
<td>#Html.DisplayFor(m => item.Location.StableName)</td>
<td>#Html.DisplayFor(m => item.CreationDate)</td>
<td>#Html.DisplayFor(m => item.LastEdited)</td>
<td>#Html.DisplayFor(m => item.ExtraNote)</td>
<td><span class="glyphicon glyphicon-copy"></span></td>
<td><span class="glyphicon glyphicon-edit"></span></td>
<td><a href="#" onclick="deleteChannel('#Url.Action("DeleteChannel", "Channel", new { id = item.ID })')">
<span class="glyphicon glyphicon-remove"></span></a>
</td>
</tr>
}
}
</table>
<br/><br/>
<div style="display: none;">
#* #{ Html.RenderPartial("_CreateChannel"); } *#
</div>
<h5>#Html.ActionLink("Opret en ny kanal", "RegisterChannel", "Channel")</h5>
<div id="cautionDiv" title="Bekræft sletning" style="display: none;">
<p style="color: red;">The channel has a location. Are you sure you want to delete?</p>
</div>
<div id="successDiv" title="Info" style="display: none;">
<p style="color: green;">Deleted</p>
</div>
This is just my approach, and is not final, if there are better solutions, please let me know
You can't call js from a codebehind, but your ajax method can return an indication for asking the user:
if (channel != null && channel.Location != null)
{
return 'cannot-delete';
}
and the ajax method would see that on it's success function, and prompt the user:
$.ajax({
url: url,
type: "POST",
cache: false,
contentType: 'application/html; charset=utf-8',
data: $("form").serialize(),
dataType: 'html',
success: function (msg) {
if (msg == 'cannot-delete') {
ShowDialogThatAsksUserToConfirm();
} else showDialog('successDiv');
},
error: function (msg) {
alert("error");
showDialog('errorDiv');
}
});
The method ShowDialogThatAsksUserToConfirm should ask for the users's confirmation in javascript, and if allowed, submit a forced delete of the record.