Unable to print data in grid - c#

I am trying to print my data coming from controller in a table but unable to do so. I am using Kendo UI template in order to print. I am attaching the code below along with the error that I am getting.
<div id="example"></div>
<script>
$.ajax(
{
type: 'POST',
url: '/default1/KendoDataAjaxHandle/',
dataType: 'json',
success: function (result) {
//Get the external template definition using a jQuery selector
var template = kendo.template($("#javascriptTemplate").html());
console.log(result);
var data = template(result); //Execute the template
$("#example").html(data); //Append the result
}
})
</script>
<script id="javascriptTemplate" type="text/x-kendo-template">
<table>
<thead>
<tr>
<th>Customer ID</th>
<th>Customer name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
# for (var i=0; i < result.length; i++){ #
<tr>
# for (var j=0; j < result[i].length; j++){ #
<td>
#= result[j] #
</td>
# } #
</tr>
# } #
</tbody>
</table>
</script>
What i am doing in the above code is making an ajax call to the action method and getting the results in JSON. Here's my controller method:
public ActionResult KendoDataAjaxHandle([DataSourceRequest]DataSourceRequest request)
{
IQueryable<Customer> products = db.Customers;
DataSourceResult result = products.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
Error that I am getting on executing the code is: result is undefined. However on consoling the results returned after ajax call, I get an object which has all the values.
How do I print those values coming back in the table? Also please correct me if I have done something wrong here. Thank in advance.

Try changing the the variable name referenced inside the template from "result" to "data" as that is what Kendo uses in its template execution code.
Example: http://dojo.telerik.com/#Stephen/ENUze
Updated Example
Showing how to iterate the object's fields(based on comment):
http://dojo.telerik.com/#Stephen/oXOJU
NOTE: this assumes that the fields are listed in the order you have specified in your comment. If the fields don't come back in this order, you will have to add code to map the field name to the column index instead of just blindly looping.
Update 2:
Updated example using exact format of returned data:
http://dojo.telerik.com/#Stephen/ipeHec
Note: you have to deal with the CustomerAltID that is in the returned data but not in the table somehow. My example chooses to remove it from list of keys to process. How you deal with it is up to you.

Related

find the records based on search using javascript?

I wrote the below code for finding the records in a table grid.
$(function () {
grid = $('#tblsearchresult');
// handle search fields key up event
$('#search-term').keyup(function (e) {
text = $(this).val(); // grab search term
if (text.length > 1) {
// iterate through all grid rows
grid.find('tr').each(function (i) {
if ($(this).find('td:eq(1)').text().toUpperCase().match(text.toUpperCase()))
$(this).css({ background: "#A4D3EE" });
});
}
else {
grid.find('tr:has(td)').css({ background: "" });
grid.find('tr').show();
} // if no matching name is found, show all rows
});
});
<table id="tblsearchresult" class="tablesorter"">
<thead>
<tr>
<th>ApplicationName</th>
</tr>
</thead>
<tbody>
<% foreach (var request in Model.ApplicationRoles)
{ %>
<tr>
<td>
<span id="appName_<%: request.Id%>">
<%: request.Application.Name%></span>
</td>
</tr>
</tbody>
</table>
EDIT Table Data
applicationame role
application1 appadministrator
app developer
application2 tester
if i given 'app'as search text need to highlight secondrow only .highlightling firstrow also because 'app' is there in role of firstrow..exact match should be highlight on every rows.please tell me.
Your code is behaving correctly. Just that you need to clear all previously highlighted rows on "keyup" of input text first.
if (text.length > 1) {
grid.find('tr:has(td)').css({ background: "" });
grid.find('tr').show();
......rest of your code.......
You need to clear the highlight before you parse. Add this statement of yours:
grid.find('tr:has(td)').css({ background: "" });
before entering this loop:
// iterate through all grid rows
grid.find('tr').each(function (i) {
...
});
Check this fiddle: http://jsfiddle.net/F3jRj/1/
And this updated fiddle with 3 columns: http://jsfiddle.net/F3jRj/2/

Delete webgrid row using javascript?

I have a webgrid in mvc3. It has the column delete. Upon clicking it, I want to run a Javascript function to redirect the user to a controller's action by passing a row id as the parameter to the Javascript function.
How would I do this? The column is not an Htmlactionlink.
Assuming this is the way you have the rows:-
<tr id="thisRowId">
.
.
.
<td>
<a id="deleteBtn" data-rowId="thisRowId">delete</a>
</td>
<tr>
Have a generic function for your delete click
$('#deleteBtn').click(function(){
var id = $(this).data('rowId'); // or use $(this).closest('tr').attr('id');
$.ajax({
url: "controller/action",
type: 'Delete', // assuming your action is marked with HttpDelete Attribute or do not need this option if action is marked with HttpGet attribute
data: {'id' : "'" + id "'"} // pass in id here
success : yoursuccessfunction
});
};
As documented here, this is an example of removing a table row from a WebGrid following an AJAX request. WebGrid doesn't make it easy to identify a particular item in the table. The issue is how to identify the row to be deleted. In the example, the MvcHtmlString is used to inject a span tag into the column. It contains an id value that is subsequently used to identify the row to be removed from the table.
<div id="ssGrid">
#{
var grid = new WebGrid(canPage: false, canSort: false);
grid.Bind(
source: Model,
columnNames: new[] { "Location", "Number" }
);
}
#grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Location", "Location"),
grid.Column("Number", "Number"),
grid.Column(
format: (item) =>
new MvcHtmlString(string.Format("<span id='ssGrid{0}'>{1}</span>",
item.SecondarySystemId,
#Ajax.RouteLink("Delete",
"Detail", // route name
new { action = "DeleteSecondarySystem", actionId = item.SecondarySystemId },
new AjaxOptions {
OnComplete = "removeRow('ssGrid" + item.SecondarySystemId + "')"
}
)
)
)
)
)
)
</div>
<script>
function removeRow(rowId) {
$("#" + rowId).closest("tr").remove();
}
</script>
You can try attaching a jQuery click handler to the element like so:
HTML:
<tr>
<td>
<a id="your id">delete</a>
</td>
<tr>
Javascript:
$("tr a").click(function() {
//your code
});

Trouble with name iterations for Html.DropDownList

I have a table where each row contains fields for a form.
I iterate in the view using this:
#foreach (var item in Model) { }
Within the foreach, I create a new table row with various fields contained inside. e.g.:
<tr><td> #Html.DropDownList("granny", "") </td></tr>
"granny" is being passed via the controller, and looks a bit like this:
ViewData["granny"] = new SelectList(db.getGrannies(), "grannyid", "grannyname");
Everything's working pretty well. The view is getting its grannies, and everything looks good. I noticed however that the name property of the field { e.g....
<select id="granny" name="granny">
} is the exact same for EVERY row created. This is a problem. I want to toss this data back to the controller in the form of a FormCollection and do fun stuff with all these grannies. I can't do that if they're not all getting passed.
That is, I'd like the selects to read, instead, like this:
<select id="granny1" name="granny1">
<select id="granny2" name="granny2">
I researched the problem a bit, and tried using
new { #Name="xyz" + n }
But Visual Studio didn't like that much.
The short and sweet of it all is this:
How do I give ViewData-generated Html.DropDownLists their own unique ids/names?
How do I give ViewData-generated Html.DropDownLists their own unique ids/names?
You cannot change the name of the generated input field and this is by design. Only the id could be changed. This being said you shouldn't need to do that. You could do the following:
#for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DropDownList(
"selectedGranny",
(IEnumerable<SelectListItem>)ViewData["granny"]
)
</td>
</tr>
}
It seems like you are either trying to databind a collection, or you just need to manually name your selects (as they are really different controls on the web form).
You can use the following overload to pass html parameters to the drop down :
#Html.DropDownList(
"CategoryID",
(SelectList)ViewBag.CategoryId,
"--Select One--",
new{ //anonymous type
name = "granny1",
#class = "myCssClass",
onchange = "someFunction();"
})

Reorder table rows, update priority in database

I have a table with rows that is sorted based on the INT Priority in my database.
Every row has a <input type="hidden" /> with an ID reference to the database. It also have some up and down arrows (class .up and .down) with the following JavaScript to move the row.
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
});
});
Now my question is, how to I update the priority in the database? I need somehow to get the order of the ID's and update the priority column - is there a neat solution for this?
Use jQuery to get a list of the IDs after you have moved a row. Something like:
var inputs = $("#myTable").find("tr").find("input");
// store each rows id in an array - this will be in the correct order
var ids = [];
inputs.each(function(){
ids.push($(this).val());
});
Then pass this list to a PageMethod or WebService and loop through the list, setting the priority of each row in the database. Obviously you will also need to take into account paging or any filtering you have applied to the items too.
Update:
You might want to also look at jQueryUI Sortable to enable drag/drop sorting. You would update the db in the same way.
Update 2:
Here is a simple delay function.
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
Then use it as follows:
delay(function () {
MySortFunction();
}, 300);
This will delay the function for x milliseconds and cancel any previous calls if you call it again within the specified time.
well, if you also update the prioirty number (index?) when you reorder two rows (),
right in the handler for 'up' / 'down' next to the row.insertBefore(row.prev());
then you could simply loot through the rows on the server and generate a simple "update x set priority = #priority where id = #id"
This may be overkill but I wanted to randomly move a row more than one row up or down. Still have to submit back to the server and this snippet doesn't have the <form> tag, but it should be pretty easy to process the inputs into a sort order based on looping through the input name form.hdrSort* values.
<cfoutput>
<script type="text/javascript">
var maxHdr=#qX.recordCount#;
var curHdr=0;
$(document).ready(function(){
bindReorder();//set with function because when the table gets regenerated, the ordering functionality gets stripped and has to be rebound to the content
});
function bindReorder(ok2do){
if(ok2do==null) ok2do=true;
$("input[id^='hdr']").each(function(){
$(this).mask("?999").focus(function(){
curHdr=parseInt($(this).val());//original value held in global js var
}).blur(function(){
var tVal=parseInt($(this).val());//entered value
if(curHdr!=tVal){
var tId =parseInt($(this).attr("id").substr(3));//id of changed value - this is the new value we don't change'
if(tVal>#qX.recordCount# || tVal<1){//validate entered is in scope
alert("please enter a positive number less than or equal to #qX.recordCount#");
$(this).val(curHdr);
}else if(ok2do){
var lo=Math.min(tVal,curHdr);//lower of original and entered values
var hi=Math.max(tVal,curHdr);//higher of original and entered values
var upDn=1;//default that entered value is less than original value
var aryHdrTbls=new Array(#qX.recordCount#+1);//zero based
if(lo==curHdr) upDn=-1;
$("input[id^='hdr']").each(function(i){
var checkVal=parseInt($(this).val());
var thisId=parseInt($(this).attr("id").substr(3));
if(checkVal<=hi && checkVal>=lo){
if(thisId!==tId) $(this).attr("value",checkVal+upDn);
else $(this).attr("value",checkVal);
aryHdrTbls[$(this).val()]=$("##tbl"+thisId).parent().html();
}
});
for(var i=lo; i<=hi; i++){
$("##td"+i).html(aryHdrTbls[i]);
}
bindReorder(false);
}
}
});
});
}
</script>
<table width="80%">
<cfloop query="qX">
<tr>
<td id="td#qX.currentRow#">
<table style="width:100%;border:1px solid gray;" id="tbl#qX.currentRow#">
<tr>
<td colspan="2" style="background-color:##dddddd;">
<div style="float:right;"><input name="hdrSort#qX.currentRow#" id="hdr#qX.currentRow#" size="1" value="#qX.currentRow#"> <input type="button" width="3" value="go"></div></td>
</tr>
<tr>
<td>#qX.currentRow# #qX.nada#</td>
<td>#qX.nada# more your content original header #qX.currentRow#</td>
</tr>
</table>
</td>
</tr>
</cfloop>
</cfoutput>
</table>

Pass dynamicaly created array from View To Controller. ASP.NET MVC v1

I have this one in View:
<%
foreach (var item in (List<MyType>)ViewData["MyTypeArray"])
{
%><tr>
<td>
<%=Html.Encode(item.Name)%>
</td>
<td>
<%=Html.CheckBox("MyTypeFlags" + item.BitNumber),
/* Model goes here*/,
new {#value = (1 << item.BitNumber)})%> // html attr
</td>
</tr>
<%
}
%>
and I want do smth like this in Controller:
foreach (var item in MyDynamicallyCreatedArray)
{
//if (["MyTypeFlags" + item.BitNumber] != 0) // This shoud be changed
}
Question is how should I declare MyDynamicallyCreatedArray and go through the cycle?
You should look at using a "view model". You basically create "Models" just for your view that contain the data items you need in your view.
I use these quite often and they are really a great way of getting data in and out of your view.
For an example you can view here: http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx
Take a look at Phil Haack's post, it gets a bit tricker with checkboxes as if a box is unchecked then it doesnt submit a value.
Model Binding to a List
http://haacked.com/archive/0001/01/01/model-binding-to-a-list.aspx

Categories