Kendo mvc Grid ClientTemplate javascript function not working - javascript

I have a Kendo mvc Grid and using client template as a column and i wrote a javascript function in the template to return the script block but its seems not working and no javascript error. I also tried to write the script to the client template directly but its not working too.
//html in client template
.Columns(columns =>
{
columns.Template(e =>
{ }).ClientTemplate(
"<div class='table-responsive'>" +
"<table border='0' class='table' >" +
...................................
"</table>" +
"</div>"+
"#=AlignDiv(Id)#"
);
})
//javascript function to return a script block as a string
<script type="text/javascript">
function AlignDiv(Id) {
var result = "<script> $('.calDiv"+Id+"').map(function () {" +
"return $(this).Height();" +
"}).get()," +
"maxHeight = Math.max.apply(null, heights);" +
"$('.calDiv" + Id + "').height(maxHeight);" +
"alert('test')<\/script>";
return result;
}
Thanks a lot,
Dennis

In order to format Kendo Grid Column value with conditionally chosen action you can use one of the suitable examples below. For more information: How Do I Have Conditional Logic in a Column Client Template?
UI for Javascript:
{
field: "EmployeeName", type: "string", width: "55px", title: "Employee Name",
template: "#= GetEditTemplate(data) #"
}
UI for MVC:
...
columns.Bound(t => t.EmployeeName)
.Title("Status Name")
.Template(#<text></text>)
.ClientTemplate("#= GetEditTemplate(data)#").Width("55px");
...
Javascript Method:
<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
var html;
if (data.StatusID == 1) {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit1", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-success'>" +
data.EmployeeName
+ "</span>"
);
}
else {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit2", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-danger'>Cancel</span>"
);
}
return html;
}
</script>

Related

Javascript - InnerHTML doesn't edit the DOM

I'm working on a project with Laravel. Now I'm coding the feature which prints all activities responsible. Before I was using foreach loop in PHP to print all of my activities (from the DB).
But now I have to use JS to print these activities because I want to add a filter (and avoid page to reload).
I have created this script in my view :
<script>
containerE = document.getElementById("container");
var request = new XMLHttpRequest();
request.open("GET","{{route('APIManifs')}}", false);
request.send(null);
responses = JSON.parse(request.responseText);
function expandResults(value){
for (var i in responses){
if (responses[i].status === value) {
containerE.innerHTML = containerE.innerHTML +
"<div class=\'col-md-5 offset-1\' id=\'1\'>" +
"<div class=\'card\'>" +
"<a href='/manif/" + responses[i].id + "'"+" ><div class=\'card-header\' style=\'text-align: center\'>"+
"<img src='"+responses[i].image+"'><br>"+
responses[i].name+" | "+responses[i].date_add+"<br>"+
"</div> </a>"+
"<div class=\'card-body\'>"+
"Nom : "+responses[i].name+"<br>"+
"Description : "+responses[i].description+"<br>"+
"</div>"+
"</div>"+
"</div>";
containerE.innerHTML = containerE.innerHTML + "Arg";
console.log(responses[i].status+"=="+value);
}
else{
console.log(responses[i].status+"<>"+value);
}
}
}
</script>
I got the information but impossible to print my HTML in the DOM! When I copy paste the inner HTML code in the console it's work.
Do you have any ideas on how to accomplish this?
Thank's in advance!

How to pass a variable in ajax append function (into html element with razor)?

I need to pass the Id of a object into a html element (razor part), but it doesn't recognize it. Look like the Id is not in its scope, or something. Is there a way to pass the value into the razor part of my html element in the append function?
$.ajax({
data: data,
url: url + "?searchTerm=" + data
}).success(function (response) {
console.log(response);
var table = $('#companyTable');
var tBody = table.children('tbody');
tBody.html("");
var textbox = document.getElementById("searchBar");
textbox.value = "";
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\"location.href='#Url.Action("Edit", "Company", new { #id = response.CompanyId })'\"> Edit</button></p>" +
"</td></tr>"
);
table.removeClass("hidden");
var originalTable = $('#originalTable');
originalTable.remove();
}).error(function (response) {
console.log(response);
});
}
Thank you.
I do those things this way:
+ "<p><button onclick=\"location.href='#(Url.Action("Edit", "Company"))?id=" + response.CompanyId + "'\">Edit</button>"
You are totally missing the concept of server-side rendering and browser execution. Consider this example, your server renders your js code, and just leaves all work to browser, then browser stars to execute Ajax request somehow(button click), when Ajax completed - you have a response value, but this value exists only inside browser context, so it doesn't make sense to pass value into razor, as it already done its work while rendering your file
Now, what to do? The simplest solution would be to hardcore Url of company edit by yourself, as razor simply doesn't know anything what's happening client-side, example:
location.href="/company/1/edit" //where 1 is id from Ajax request
The easiest complete solution is
public ActionResult WhateverMethod()
{
// ....
var urlHelper = new UrlHelper(this.ControllerContext.RequestContext);
response.Url = Url.Action("Edit", "Company", new { #id = response.CompanyId });
// ....
}
And
tBody.append(
"<tr><td>" +response.CompanyName + " </td><td>"
+ response.CompanyIdNumber + "</td><td>"
+ response.CompanyTaxNumber + "</td><td>"
+ "<p><button onclick=\"location.href='" + response.Url + "'\"> Edit</button></p>"
+ "</td></tr>");
Calling a Razor methods in JavaScript is going to cause you nothing but grief.
response.CompanyId is considered as string , so try by concatenating it as below
var a="location.href='#Url.Action("Edit", "Company", new{#id='"+response.CompanyId+"'})'"
response.CompanyId ( "<tr><td>" +response.CompanyName + " </td><td>" +
response.CompanyIdNumber + "</td><td>" +
response.CompanyTaxNumber + "</td><td>" +
"<p><button onclick=\""+a +"\"> Edit</button></p>" + "</td></tr>")

JSON and JavaScript integration when formatting a SPARQL query in HTML

I have an HTML + SPARQL + JSON + JavaScript program that works correctly, shown here: http://ontomatica.com/public/test/clavius.html
Here is the SPARQL + JSON + JavaScript code:
function retrieveData() {
var query = "PREFIX : <http://dbpedia.org/resource/> PREFIX dbp: <http://dbpedia.org/ontology/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dbpprop: <http://dbpedia.org/property/> SELECT ?person ?b_date ?d_date ?abstract ?thumbnail WHERE { ?person rdf:type dbp:Person ; dbp:birthDate ?b_date ; dbp:deathDate ?d_date ; dbp:abstract ?abstract . OPTIONAL { ?person dbp:thumbnail ?thumbnail } FILTER ( ?b_date >= '1488-01-01'^^xsd:date && ?b_date < '1600-01-01'^^xsd:date && ?d_date < '1650-01-01'^^xsd:date ) FILTER ( langMatches(lang(?abstract), 'EN')) } ORDER BY ?person ?b_date";
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['person']['value'].replace("http://dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> (" + value['b_date']['value'] + " - " + value['d_date']['value'] + ")</h3></div>";
if (value['thumbnail'] != null)
html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
else
html += "<div class='inline thumb'><img src=''/></div>";
html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";
$('#output_div').append(html);
}
);
}
However, a new version of the program does not work correctly. Here are the components.
The modified SPARQL query works correctly:
PREFIX : <http://dbpedia.org/resource/>PREFIX dbp: <http://dbpedia.org/ontology/>PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>PREFIX dbpprop: <http://dbpedia.org/property/>SELECT ?food ?abstract ?thumbnail ?caption WHERE { ?food rdf:type dbp:Food ; dbpprop:name ?name ; dbpprop:caption ?caption ; dbp:abstract ?abstract . OPTIONAL { ?food dbp:thumbnail ?thumbnail } FILTER ( regex(?name, "Calzone" )) FILTER ( langMatches(lang(?abstract), "EN"))} ORDER BY ?food
I've tested the query on the DBpedia Virtuoso SPARQL end point. Here is the result:
http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=PREFIX+%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2F%3EPREFIX+dbp%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3EPREFIX+rdf%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%3EPREFIX+dbpprop%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fproperty%2F%3ESELECT+%3Ffood+%3Fabstract+%3Fthumbnail+%3Fcaption+WHERE+{+%3Ffood+rdf%3Atype+dbp%3AFood+%3B+dbpprop%3Aname+%3Fname+%3B+dbpprop%3Acaption+%3Fcaption+%3B+dbp%3Aabstract+%3Fabstract+.+OPTIONAL+{+%3Ffood+dbp%3Athumbnail+%3Fthumbnail+}+FILTER+%28+regex%28%3Fname%2C+%22Calzone%22+%29%29+FILTER+%28+langMatches%28lang%28%3Fabstract%29%2C+%22EN%22%29%29}+ORDER+BY+%3Ffood&format=text%2Fhtml&timeout=30000&debug=on
So far, so good.
Here is the modified JSON + JavaScript program (with the operational SPARQL query).
function retrieveData() {
var query = "PREFIX : <http://dbpedia.org/resource/>PREFIX dbp: <http://dbpedia.org/ontology/>PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>PREFIX dbpprop: <http://dbpedia.org/property/>SELECT ?food ?abstract ?thumbnail ?caption WHERE { ?food rdf:type dbp:Food ; dbpprop:name ?name ; dbpprop:caption ?caption ; dbp:abstract ?abstract . OPTIONAL { ?food dbp:thumbnail ?thumbnail } FILTER ( regex(?name, "Calzone" )) FILTER ( langMatches(lang(?abstract), "EN"))} ORDER BY ?food";
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['food']['value'].replace("http://dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> (" + value['caption']['value'] + ")</h3></div>";
if (value['thumbnail'] != null)
html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
else
html += "<div class='inline thumb'><img src=''/></div>";
html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";
$('#output_div').append(html);
}
);
}
Here are the differences between the correct program and the incorrect program.
The DBpedia ontology term is changed from 'person' to 'food'.
The query field to be formatted in HTML output (encoded by <div><h3></div></h3>) is changed from ['b_date'] to ['caption'].
I suspect the problem is local to the $.ajax clause and the JSON.stringify statement:
$('#raw_output').text(JSON.stringify(data, null, 3));
Bottom line: I would like to generalize the first program for other applications, but am fumbling the JSON statements.
Why does the second program fail when it is based on the first program? What am I doing wrong?
Is there a better way to generalized the program (1) for other SPARQL queries with different terms; (2) with different numbers of terms; (3) for a SPARQL query of federated databases (only DBpedia is used in the example, but I'd like to format terms from a federated query - mashing up data from different RDF triplestores).
Working Example
Non-working Example
The problem is that you've got unescaped quotes in the second query, which means that the Javascript engine sees a syntax error (an unexpected identifier). The relevant part is in:
var query = "…FILTER ( regex(?name, "Calzone" )) FILTER ( langMatches(lang(?abstract), "EN"))} ORDER BY ?food";
Notice in the syntax highlighting that the string ends at the " immediately before Calzone, etc.
I found this by looking at the Javascript console in Google Chrome when loading your second sample page:
You can fix this by doing:
var query = "…FILTER ( regex(?name, 'Calzone' )) FILTER ( langMatches(lang(?abstract), 'EN'))} ORDER BY ?food";
Once you've done that, you get the kinds of results you'd expect:

Form in jQuery UI Dialog Cached.

I'm a C/C++ programmer and new to javascript. The following code is giving me grief and I don't really know what I'm doing wrong. I've searched and can't find where others have had the same problem.
I've taken my project and cut out my problem code to try and understand and fix it. The short version is when I click my "Enter data" image on an HTML page, it creates a dialog box with a form and table of inputs (with default data) and I enter/change some data. When I click the dialog box save button, it goes through JSON.stringify($('#form').jsonify()) to collect the form data and brings up an alert box showing the data that I entered. This part works fine.
If I click the "Enter data" image again, the dialog box comes up and I enter/change new data. When I click the dialog box save button, it brings up an alert box showing the previous data that I saved (in this case showed in the alert box).
No matter how many times I try it, it always returns the data form the very first entry and never any of the new(er) data.
What am I doing wrong?
Some references:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="~/Scripts/test.js"></script>
<link href="~/Content/jquery/themes/ui-lightness/jquery-ui.min.css" rel="stylesheet" />
My HTML code
<div>
<img id="additem"
Title="Add Item"
onclick="addstuff(this)"
OnMouseOver="this.style.cursor='pointer';"
OnMouseOut="this.style.cursor='default';"
src="~/images/Sign_Add_Icon_32.png" />
</div>
My test.js file.
$.fn.jsonify = function (options) {
var settings = $.extend({
stringify: false
}, options);
var json = {};
$.each(this.serializeArray(), function () {
if (json[this.name]) {
if (!json[this.name].push)
json[this.name] = [json[this.name]];
json[this.name].push(this.value || '');
} else
json[this.name] = this.value || '';
});
if (settings.stringify)
return JSON.stringify(json);
else
return json;
}
function addstuff(obj) {
var strHtml = "";
var strHtml = "<div class=\"container\" id=\"addphonedlg\" title=\"Add Phone\" overflow:\"auto\">"
+ "<p>Please enter the following information.</p>"
+ "<form id=\"form\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">"
+ "<tr><td align=\"right\"><label for=\"name\">" + "Data 1" + ":</label></td>"
+ "<td><input type=\"text\" name=\"" + "data1" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 1 data" + "\" />" + "</td></tr>"
+ "<tr><td align=\"right\"><label for=\"name\">" + "Data 2" + ":</label></td>"
+ "<td><input type=\"text\" name=\"" + "data2" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 2 data" + "\" />" + "</td></tr>"
+ "<tr><td align=\"right\"><label for=\"name\">" + "Data 3" + ":</label></td>"
+ "<td><input type=\"text\" name=\"" + "data3" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 3 data" + "\" />" + "</td></tr>"
+ "</table></form>"
+ "</div>";
$(strHtml).dialog({
autoOpen: false,
width: 400,
modal: true,
buttons: {
"Save": function () {
alert("Add information " + JSON.stringify($('#form').jsonify()));
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function () {
$(this).siblings('.ui-dialog-buttonpane').find("button:contains('Cancel')").focus();
}
}).dialog('open');
}
This seems to be a known problem of forms in ui dialogs being cached. But you need to remove the form onClose of the dialog.
I added close event function to your code. You should be fine now.
$(strHtml).dialog({
autoOpen: false,
width: 400,
modal: true,
close: function( event, ui ) {
$('#form').remove(); // this where the problem is
},
buttons: {
Save: function () {
alert("Add information " + JSON.stringify($('#form1').jsonify()));
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function () {
$(this).siblings('.ui-dialog-buttonpane').find("button:contains('Cancel')").focus();
}
}).dialog('open');
}

JQuery Append/Html not working in IE7/8/8compatmode but does in FF/Chrome/Opera

Going crazy trying to find this. Any help would be appreciated.
Problem is that this code does 'nothing' in IE7/8/8compatmode. Works fine in Chrome 15.0.8 and FF3.5, as well as Opera 11.60.
It uses a xml file to read via ajax, and then places it in the table. I've tried several things I'll detail after the code.
XML:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<issues>
<issue>
<id>12</id>
<emp>44</emp>
<author>1</author>
<comments>Example comments go here</comments>
<issueDate>12/5/2011</issueDate>
<modifiedBy />
<modifiedDate />
<modifiedComments />
<pending>true</pending>
<valid>false</valid>
</issue>
</issues>
javascript:
<script type="text/javascript">
$(document).ready(function () {
grabIssues('2011/12/01', '2011/12/13');
});
function grabIssues(startDate, endDate) {
$.ajax({
type: "POST",
url: "Ajax/mtlIssues.aspx",
data: {
startDate: startDate,
endDate: endDate
},
dataType: ($.browser.msie) ? "text" : "xml",
success: function (result) {
createIssues(result);
}
});
}
function createIssues(xml) {
var data = "";
//newIssueArray = [];
$("issue", xml).each(function (id) {
message = $("issue", xml).get(id);
$id = $("id", message).text();
$emp = $("emp", message).text();
$author = $("author", message).text();
$comments = $("comments", message).text();
$issueDate = $("issueDate", message).text();
$pending = $("pending", message).text();
$valid = $("valid", message).text();
//$("#empList").append("<tr><td>" + $emp + "</td><td>" + $issueDate + "</td><td>" + $comments + "</td><td>" + $pending + "</td></tr>");
//newIssueArray.push("<tr><td>" + $emp + "</td><td>" + $issueDate + "</td><td>" + $comments + "</td><td>" + $pending + "</td></tr>");
data += "<tr><td>" + $emp + "</td><td>" + $issueDate + "</td><td>" + $comments + "</td><td>" + $pending + "</td></tr>";
});
//$("#empList").html("");
//for (i in newIssueArray) {
//$("#empListDetails").append(newIssueArray[i]);
//data += newIssueArray[i];
//}
//$("#empList").append("</table>");
$("#empListDetails").html(data);
}
</script>
partial html
<div id="empList" class="ui-widget">
<table id='empListTable'>
<thead>
<tr><th>Name</th><th>Date</th><th>Comments</th><th>Pending</th></tr>
</thead>
<tbody id='empListDetails'></tbody>
</table>
</div>
What I've tried:
As you can tell by commented code left in, I've tried everything from creating an array to using a variable, to directly appending each to the page as it is detected.
I've also tried to have just a blank div (empList) and create the
entire table in the javascript and use the .html() to insert it.
Didn't work. Nor did append.
I've coded this several ways, and all work in FF/Chrome/Opera. But I
can't even get IE7/8/8compatmode to even give me an error. Just
nothing happens
I upgraded JQuery to 1.7.1 from 1.4.2 and tried all variations again.
Hoping it was perhaps a bug caught by the Jquery team and not my code
directly. Didn't work.
Also note, I removed the 'modified' portions from the javascript. It
was there, but the issue has persisted before/after.
This shows nothing entered at all on the f12/dev console in IE8.
Isn't placing any text at all in there.
Any assistance would be appreciated.
never iterate the xml using DOM traversal methods, its very browser specific, try using $.parseXML

Categories