I'm trying to pass two arguments to the Authorization.js file. It is used to search in the variables that I sent from Index.cshtml file.
Here at the end of the Index.cshtml file
<script src="~/AreasFolder/Authorization/js/Authorization.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var fork = '#Html.Raw(Json.Serialize(new ImOnTech.Hukuk.Web.Repository.RoleTreeRepository(_configuration).TaskItemRolsuzGetir()))';
sayfaGruplariArray = JSON.parse(fork);
var exec = '#Html.Raw(Json.Serialize(new ImOnTech.Hukuk.Web.Helpers.UserHelper(_roleManager).GetRoles()))';
rollerArray = JSON.parse(exec);
$("#sayfaAraTable").toggle(false);
$('#sayfaAraTextbox').keyup(function () {
sayfalariFiltrele(true);
});
$("#sayfaGrubuAraTable").toggle(false);
$('#sayfaGrubuAraTextbox').keyup(function () {
sayfaGruplariniFiltrele(true);
});
$("#kullaniciAraTable").toggle(false);
$('#kullaniciAraTextbox').keyup(function () {
kullanicilariFiltrele(true);
});
$("#rolAraTable").toggle(false);
});
In the controller, string ItemName returns NULL from Authorization.js:
Finaly, Authorization.js file:
var sayfaGruplariArray;
var rollerArray;
function sayfalariFiltrele(isAutoComplete) {
var content = $('#sayfaAraTextbox').val();
if (content.length == 0 && isAutoComplete) {
$("#sayfaAraTable").toggle(false);
//$("tr:not(:first)", "#sayfaAraTable").remove();
}
else {
//$("tr:not(:first)", "#sayfaAraTable").remove();
$.ajax({
url: "/Authorization/Item/SayfaAra",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
itemName: content
}),
beforeSend: function (xhr) {
//jQuery.blockUI({ message: 'Lutfen bekleyiniz', baseZ: 2000 });
$('#sayfaAraTextbox').addClass('textboxLoadinggif');
},
success: function (result) {
if (result.ErrorCode == "0") {
$("#sayfaAraTable").toggle(true);
var html = "";
var sayfalarArray = result.SayfaListesi;
if (sayfalarArray.length > 0) {
html += "<tr>";
html += "<th>İşlem adı</th>";
html += "<th>Açıklama</th>";
html += "<th>URL</th>";
html += "<th>Menüde görünsün</th>";
html += "<th style='width:1%'></th>";
html += "</tr>";
}
for (i = 0; i < sayfalarArray.length; i++) {
html += "<tr id='sayfaTr" + sayfalarArray[i].AuthorizationItemKey + "'>";
html += "<td>" + sayfalarArray[i].ItemName + "</td>";
html += "<td>" + sayfalarArray[i].Description + "</td>";
html += "<td>" + sayfalarArray[i].MenuLinkUrl + "</td>";
html += "<td>" + sayfalarArray[i].DisplayInMenu + "</td>";
html += "<td nowrap><a href=\"javascript:SayfaBilgisiniGetir(" + sayfalarArray[i].AuthorizationItemKey + ")\"title='Güncelle'><i class='fa icon-pencil fa-2x'></i></a> <a href='javascript:SayfaSilUyari(" + sayfalarArray[i].AuthorizationItemKey + ")' title='Sil'><i class='fa icon-trash fa-2x'></i></a></td>";
html += "</tr>";
}
//$("#sayfaAraTable").append(html);
$("#sayfaAraTable").html(html);
}
else {
$("#sayfaAraTable").toggle(false);
toastr.warning(result.Result, "Uyarı", { timeOut: 3000 });
}
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
},
failure: function (xhr, ajaxOptions, thrownError) {
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
$("#sayfaAraTable").toggle(false);
toastr.error("script failure: " + xhr.responseText, "Uyarı", { timeOut: 3000 });
},
error: function (xhr, ajaxOptions, thrownError) {
$('#sayfaAraTextbox').removeClass('textboxLoadinggif');
$("#sayfaAraTable").toggle(false);
toastr.error("script error: " + xhr.responseText, "Uyarı", { timeOut: 3000 });
}
});
}
}
Any idea? What cause this problem? Thank you in advance.
You should use [FromBody] to get the json format data. Change it like below:
$.ajax({
//...
contentType: "application/json; charset=utf-8",
data: JSON.stringify(content),
//...
})
Controller:
public ActionResult SayfaAra([FromBody]string itemName)
Related
I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}
Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}
I want to display image from my database which stores the path to the image's location. Following code gives me the image path only in the output. What changes do I need to make in order for image to appear instead of image path?
GetBusinessCategoryList: function () {
debugger;
var data = JSON2.stringify({
});
$.ajax(
{
contentType: "application/json; charset=utf-8",
type: 'POST',
url: 'http://localhost:44719/Modules/BusinessCategoryView/Service/BusinessCategoryWebService.asmx/GetAllBusinessCategory',
dataType: 'json',
data: data,
success: function (result) {
alert("ok");
var returnedData = result;
BusinessManagement.BindBusinessCategoryList(returnedData);
},
error: function (error) {
alert("error");
}
});
},
BindBusinessCategoryList: function (data) {
debugger;
var cLst = data.d;
if (cLst.length > 0) {
headElements += '<table id="customerTable" cellspacing="0" cellpadding="0" >';
headElements += '<thead class="sfHeadingone">';
headElements += '<tr><th align="left">Category Image</th>';
;
headElements += '</thead>';
$('#tblGrid').html(headElements);
var i = 0;
if (i === 0) {
bodyElements += '<tbody>';
}
$.each(cLst, function (index, value) {
bodyElements += "<td>" + value.CategoryImage + "</td>";
}
});
Use img to display an image. Pass the image url to the src attribute of the img tag
bodyElements += "<td><img src='" + value.CategoryImage + "'></td>";
I have a jquery save function like this -
$(".SaveBtn").click(function () {
if ($("#Form1").valid()) {
var rowData = $("#TestTable").getRowData($(this).data("rowid"));
var currentRow = $(this).closest("tr");
var postData = {
testID: rowData.testID,
testNotes: currentRow.next().find(".NotesEntry").val(),
isActive: currentRow.next().next().find(".CheckEntry") == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
$.ajax({
type: "POST",
url: "../Services/test.asmx/UpdateTestRowData",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
$("#TestTable").setGridParam({ postData: { myID: $('#hfmyID').val() }, datatype: 'json' }).trigger("reloadGrid");
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
});
The problem is with this line -
isActive: currentRow.next().next() == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
When currentRow.next().next() is not available, the isActive is not set as "false" and is even not in the request body to web service.
Currently the request body is {"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST"}
I expect it to be -
{"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST", "isActive":"false"}
Why the "isActive" parameter is missed and how to make it available when currentRow.next().next() is not available?
Thanks
I fixed the problem by adding the else part in the following statement -
if (data.d.IsActived) {
output += "<td colspan='6' align=\"left\"><input type='checkbox' id='cbActive" + rowId + " checked" + " name='cbManualDeactive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
else {
output += "<td style=\"display:none;\"><input type='checkbox' id='cbActive" + rowId + " name='cbActive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
Thanks
Here is my submit button written dynamically through AJAX:
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
I am trying to rerun the updatefilters() function to change the items that are displayed. I imagine its a bit tough to conceptualize without seeing all the code...but essentially, all I need to do is run the function again on each click of the submit button...right now, its giving me a updatefilters is undefined error in firebug.
Heres my whole JS for reference
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var i = 0;
var page;
if(! page){
page = 0;
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, page: page },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
});
There appears to be a few problems with this approach.
First, you're not actually calling the function in your onclick handler.
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
should be:
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters();' /></li"
Second, the updatefilters function isn't accessible from the global scope, which is where that anonymous function will be executed from. You'd have to move function updatefilters(ev, ui) outside the onload callback, perhaps to the top of your script block.
On a code I wrote...
function change_regione(handle) {
// Hiding selects that we don't need
jQuery("select#comune").hide();
jQuery("select#quartiere").hide();
if(jQuery("#regione").val() == '') {
jQuery("select#provincia").parent().hide();
return
}
jQuery.ajax( {
url : WEBSITE_PATH + 'loadProvince.php',
type : 'GET',
dataType: 'json',
data : {
search_value : jQuery("#regione option:selected").attr("rel")
},
success : function(result) {
var provinceOptions = "<option value=\"\">Tutte le province</option>";
jQuery.each(result,function(i,el){
provinceOptions += '<option value="'+ el.url +'" rel="'+ el.id +'">' + el.value.replace("~","") + '</option>';
});
jQuery("select#provincia").parent().show();
jQuery("select#provincia").html(provinceOptions).show();
},
error : function(request, status, error) {
}
});
}
IE7/8 launches the AJAX request twice on the onchange() event for a select.
<select id="regione" name="regione" class="srhbox" onchange="change_regione(this)">
...
</select>
Firefox, Safari, Chrome, behave correctly.
What's going on? Have you ever seen this behaviour?
Well I am not sure why you are using inline js with jQuery.
Just use jQuery's .change() event:
$('#regione').change(function () {
// Hiding selects that we don't need
jQuery("select#comune").hide();
jQuery("select#quartiere").hide();
if (this.value == '') {
jQuery("select#provincia").parent().hide();
return;
}
jQuery.ajax({
url: WEBSITE_PATH + 'loadProvince.php',
type: 'GET',
dataType: 'json',
data: {
search_value: jQuery("option:selected", this).attr("rel")
},
success: function (result) {
var provinceOptions = "<option value=\"\">Tutte le province</option>";
jQuery.each(result, function (i, el) {
provinceOptions += '<option value="' + el.url + '" rel="' + el.id + '">' + el.value.replace("~", "") + '</option>';
});
jQuery("select#provincia").parent().show();
jQuery("select#provincia").html(provinceOptions).show();
},
error: function (request, status, error) {}
});
});
I don't know why it behaves like this but I have a work around for you. Try this.
var requestInProgress = false; // Variable to check if the request is in progress
function change_regione(handle) {
if(requestInProgress){
return;
}
requestInProgress = true;
// Hiding selects that we don't need
jQuery("select#comune").hide();
jQuery("select#quartiere").hide();
if(jQuery("#regione").val() == '') {
jQuery("select#provincia").parent().hide();
return
}
jQuery.ajax( {
url : WEBSITE_PATH + 'loadProvince.php',
type : 'GET',
dataType: 'json',
data : {
search_value : jQuery("#regione option:selected").attr("rel")
},
success : function(result) {
var provinceOptions = "<option value=\"\">Tutte le province</option>";
jQuery.each(result,function(i,el){
provinceOptions += '<option value="'+ el.url +'" rel="'+ el.id +'">' + el.value.replace("~","") + '</option>';
});
jQuery("select#provincia").parent().show();
jQuery("select#provincia").html(provinceOptions).show();
requestInProgress = false;
},
error : function(request, status, error) {
}
});
}