Active or Inactive on Button click in ASP.Net MVC? - javascript

I am getting return json data from server,every value is inserted in table except status.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
if (item.Status == "Y") {
item.Status = + '<img src="~/img/Active.png" height="32" width="32"/>'
}
else (item.Status == "N")
{
item.Status = + '<img src="~/img/InActive.png" height="32" width="32"/>'
}
var t = i + 1;
var rows = "<tr>"
+ "<td>" + t + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + '' + item.Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
}
if item.Status == "N" means InActive image will display and if item.Status == "Y" means Active image will display
But in my code Status Value i didn't get any idea.?
Controller:
public ActionResult ViewModules(int id)
{
Domain_Bind();
dynamic mymodel = new ExpandoObject();
userType type = new userType();
List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
List<ViewRoleModules> RoleList;
List<ViewRoleModules> role = new List<ViewRoleModules>();
foreach (ViewRoleModules emp in EmpList)
{
RoleList = type.GetSiteRoleModulesViews(emp.ModuleID);
foreach (ViewRoleModules vip in RoleList)
{
role.Add(new ViewRoleModules
{
RoleName = vip.RoleName,
ModuleID = vip.ModuleID
});
}
}
var data = new { EmpList = EmpList, role = role };
return Json(data, JsonRequestBehavior.AllowGet);
}

Your code is a bit of a mess to be honest with several syntax errors. Hope this helps:
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
var roleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
var moduleName = item.ModuleName;
if (item.ParentModuleID == -1) {
moduleName = " -- " + moduleName;
}
var status = '';
if (item.Status == "Y") {
status = '<img src="~/img/Active.png" height="32" width="32"/>';
} else {
status = '<img src="~/img/InActive.png" height="32" width="32"/>';
}
var row = "<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + moduleName + "</td>" +
"<td>" + item.Url + "</td>" +
"<td>" + roleName[i].RoleName + "</td>" +
"<td>" + status + "</td>" +
"</tr>";
$('#example tbody').append(row);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});

Related

Search in .net MVC with AJAX. What can I do for the following code?

I want to do a search with AJAX. I simply did with the get method through passing search string in controller but that not I want
Below my controller code, where I get the search value from URL and return DATA (which is a list)
if (search != null)
{
if (search.ToLower().ToString() == "paid")
{
DATA = DATA.Where(a => a.Purchased_Price > 0).ToList();
}
else if (search.ToLower().ToString() == "free")
{
DATA = DATA.Where(a => a.Purchased_Price == 0).ToList();
}
else
{
DATA = DATA.Where(a => a.Purchased_File_Name.ToLower().StartsWith(search.ToLower()) || a.Purchased_Category.ToLower().StartsWith(search.ToLower()) || a.User1.Email.ToLower().StartsWith(search.ToLower()) || a.Purchased_Price.ToString().StartsWith(search)).ToList();
}
ViewBag.SoldList = DATA.ToPagedList(page ?? 1, pageSize); *this is what I actually did*
return Json(DATA , JsonRequestBehavior.AllowGet); *this is trial I do not know this work or not*
}
Below is the script which I wrote in view. Where I am going wrong? I'm not aware of that. I want whatever list comes with the help of whatever search I entered. To be printed in the table. Table is just above this script; I don't think it's needed so I did not include that.
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var search_value = $("#searchText").val();
alert(search_value);
var SetData = $("#tabledata"); *tabledata is id of tbody tag *
SetData.html("");
console.log("setddata");
console.log(SetData);
$.ajax({
type: "get",
url: "/Home/MySoldNotes?search=" + search_value, *home is controller, mysoldnotes is action*
contentType: "application/ json; charset = utf - 8",
dataType: "html",
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
You must pass object to controller from ajax call. Example
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var objParam = new Object();
objParam.search_value = $("#searchText").val();
$.ajax({
type: "POST",
url: "/Home/MySoldNotes"
contentType: "application/json; charset = utf-8",
data: JSON.stringify(objParam)
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
Then in your controller
public JsonResult MySoldNotes(string search_value)
{
// Do whatever and return json as result
}
List<BuyerReq> DATA = dc.BuyerReqs.Where(a => a.seller_id == ab && a.Status == true).AsQueryable().ToList();
return Json(DATA, JsonRequestBehavior.AllowGet);
while returning from the controller I am getting an error(not success my AJAX call).
but when I am doing this for testing purpose :
var aa = "checking"; return Json(aa, JsonRequestBehavior.AllowGet);
this works. I am not getting the exact error.

How to retrieve files from Sharepoint Document library Folders

I have two folders in my document library, that two folders are created automatically based on the year when the file was uploaded. Now what I need to do is Retrieve the file from multiple files.How can I achieve this using javascript...
My Function for Uploading file and create a folder based on year
onclick="fileUpload('Improvement-Projects','improvementprojects')
function fileUpload(divId , fileId) {
var clientContext;
var oWebsite;
var oList;
var itemCreateInfo;
var resultpanel = "MySite";
clientContext = new SP.ClientContext.get_current();
oWebsite = clientContext.get_web();
oList = oWebsite.get_lists().getByTitle("QualityCI");
itemCreateInfo = new SP.ListItemCreationInformation();
itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
var d = new Date();
var n = d.getFullYear();
var dynfloder = itemCreateInfo.set_leafName(divId + '-' + n.toString());
alert(dynfloder);
this.oListItem = oList.addItem(itemCreateInfo);
this.oListItem.update();
clientContext.load(this.oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
And function to retrieve the files
var d = new Date();
var n = d.getFullYear();
fileGetAction("/sites/Sitename/QualityCI" + '/' + divId + '-' + n.toString());
function fileGetAction(folderUrl) {
if ($.fn.DataTable.isDataTable('#table_id')) {
$('#table_id').DataTable().destroy();
}
$('#table_id tbody').empty();
var requestURL = _spPageContextInfo.webAbsoluteUrl
+ "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files";
$.ajax({
url: requestURL,
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
complete: function (data) {
console.log("folder: " + folderUrl + " - files: ", data);
var dynamicTable = "";
for (j = 0; j < data.responseJSON.d.results.length; j++) {
var tableData = data.responseJSON.d.results[j];
dynamicTable += "<tr>";
dynamicTable += "<td>" + tableData.Name.split('.').slice(0, -1).join('.') + "</td>";
dynamicTable += "<td>" + ' "' + tableData.Name + '"' + "</td>";
dynamicTable += "<td class='text-center'>" + '<a class="btn btn-primary delete" onclick="javascript: fileDeleteAction(\'' + tableData.ServerRelativeUrl + '\',\'' + folderUrl + '\');">Delete</a>' + "</td>";
dynamicTable += "</tr>";
}
document.getElementById("datatable").innerHTML = dynamicTable;
table = $('#table_id').DataTable();
},
error: function (err) {
console.error("Error: ", err);
}
});
}
This is working fine.But my requirement is if the folder name is Improvement-Projects-2020 then that folder data only I can retrieve I want to retrieve Improvement-Projects-2019 files also Please help me
Use promise, you could request multiple requests and get return data from these requests and then bind the data.
Sample script:
<script>
var d = new Date();
var n = d.getFullYear();
fileGetAction("/sites/dev/QualityCI" + '/Improvement-Projects-' + n.toString(),"/sites/dev/QualityCI" + '/Improvement-Projects-' + (n-1).toString());
function fileGetAction(...args) {
if(arguments.length==0){
console.log("There is no corresponding folder in the library")
return;
}
var reqs=new Array()
$('#table_id tbody').empty();
var dynamicTable = "";
for(var i=0;i<args.length;i++){
var folderUrl=args[i]
var requestURL = _spPageContextInfo.webAbsoluteUrl+ "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files";
reqs[i] = _ajax(requestURL)
}
Promise.all(reqs).then((result) => {
var dynamicTable = "";
for (j = 0; j < result.length; j++) {
for(var x=0;x<result[j].d.results.length;x++){
var tableData = result[j].d.results[x]
dynamicTable += "<tr>";
dynamicTable += "<td>" + tableData.Name.split('.').slice(0, -1).join('.') + "</td>";
dynamicTable += "<td>" + ' "' + tableData.Name + '"' + "</td>";
dynamicTable += "<td class='text-center'>" + '<a class="btn btn-primary delete" onclick="javascript: fileDeleteAction(\'' + tableData.ServerRelativeUrl + '\',\'' +args[j] + '\');">Delete</a>' + "</td>";
dynamicTable += "</tr>";
}
}
document.getElementById("datatable").innerHTML = dynamicTable;
table = $('#table_id').DataTable();
}).catch((error) => {
console.log(error)
})
}
function _ajax(requestURL){
return new Promise((resolve, reject) => {
$.ajax({
url: requestURL,
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function(data) {
resolve(data)
},
error: function(error) {
reject(error)
}
})
})
}
</script>

Pass option value from one function to another function

I have a function like this:
$('input[type=radio][name=editList]').change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function (data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" +item.ID+item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
I want to get that item.ID to use into another function as:
$(function getCuadrilla() {
var items = "";
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
I try to use $('input[type=radio][name=editList]').val() as
$(function getCuadrilla() {
var items = "";
$('input[type=radio][name=editList]').val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
but instead item.ID I receive string "Proveedor", can any one explain me how can I access to item.ID? Regards
Complete JS:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.ID + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("
GetUnidades ", "
Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Codigo + "-" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + " " + item.Apellido + "</option>";
});
$("#lstProveedor").html(items);
});
}
});
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
});
As James comment, I try it and JS hit first line but it donĀ“t pass over there
Update:
New js structure:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.ID +
item.NombreComercial +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("GetUnidades", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Codigo +
"-" +
item.Nombre +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Nombre +
" " +
item.Apellido +
"</option>";
});
$("#lstProveedor").html(items);
});
}
});
$("#lstProveedor").change(function() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});
});
</script>
You can try this. Keep in mind that the ID you are passing to the handler function is either a provider id or a sucursal id or a usuario id, depending on which radio button populated the drop down the first time around. Also this handler will remain on the dropdown even when it has been populated by Cuadrillas.
Change
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
to
$("#lstProveedor").change(function (e) {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});

get selected row id jquery datatable row selection

i cannot get selected row id. I'm using datatable row selection. I'm getting [],[""] in console log. I have looked for other questions on SO and tried but no help
My javascript code is
$(document).ready(function () {
var selectedids = [];
var otable = $('#Table1').DataTable({
"bSort": false,
"rowCallback": function (row, data) {
if ($.inArray(data.DT_RowId, selectedids) !== -1) {
$(row).addClass('selected');
}
}
});
$('#Table1 tbody').on('click', 'tr', function () {
var id = this.id;
var index = $.inArray(id, selectedids);
var ids = $.map(otable.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
if (index === -1) {
selectedids.push(id);
console.log(selectedids);
} else {
selectedids.splice(index, 1);
}
$(this).toggleClass('selected');
});
});
I'm filling up my datatable with json data from controller in mvc
$('#ID').change(function () {
$("#t1 tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("")',
dataType: 'json',
data: { id: $("#ID").val() },
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td>" + item.id + "</td>"
+ "<td>" + item.yyy + "</td>"
+ "<td>" + item.aaa + "</td>"
+ "<td>" + item.eee + "</td>"
+ "<td>" + item.yyygg + "</td>"
+ "</tr>";
$('#Table1 tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
You could spare yourself a lot of pain, if you used dataTables select extension :
var table = $('#example').DataTable({
select: {
style: 'multi'
}
})
var selectedIds = [];
table.on('select.dt', function(e, dt, type, indexes) {
selectedIds.push(indexes[0]);
console.log(selectedIds);
})
table.on('deselect.dt', function(e, dt, type, indexes) {
selectedIds.splice(selectedIds.indexOf(indexes[0]), 1);
console.log(selectedIds);
})
demo -> http://jsfiddle.net/0w1p7a3s/

Why doesn't the code enter each block?

I need to select all the check boxes, that are checked and then get the value of id attribute.
I am doing the following way :
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
But there is a problem. The code never enters the each block. What could be the reason for this?
EDIT:
Here is the code that adds checkboxes with class selectioncheckbox:
$('#teamcheckbox_a').change(function() {
if($(this).is(':checked')) {
$('#teamcheckbox_b').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_a option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_a option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
$('#teamcheckbox_b').change(function() {
if($(this).is(':checked') ) {
$('#teamcheckbox_a').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_b option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_b option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
Either the code isn't being called at all, or $("input:checkbox[class=selectioncheckbox]") has a length of 0 (which is most likely caused by running the code before the elements have been added to the DOM, in which case you can resolve it with a ready handler).
Use as selector: $(".selectioncheckbox:checked") because i guess selectioncheckbox is only applied to checkboxes and no need to check for checked state inside each loop.
And your issue was none element was matched because using attribute selector [class=selectioncheckbox] if more than one class set on same element, this doesn't match.
The script is calling before the elements added to the DOM. So the script is unable to identify the class name and the length will be 0. Call the script in the ready handler as follows.
$(document).ready(function(){
var c= 0;
var pnames = [];
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
});

Categories

Resources