I want to send parameter when clicking a tag to controller but always null.
How can I get parameters when using datatable ajax? Please help me.
My code in controller:
public JsonResult Getdata(string isvk)
{
var orders = from o in db.Orders
select o;
if (isvk == null)
{
return Json(new { data = orders }, JsonRequestBehavior.AllowGet);
}
switch (isvk)
{
case "canceled":
orders = db.Orders.Where(o => o.Status == -1 || o.Status == -2);
break;
case "pending":
orders = db.Orders.Where(o => o.Status == 0);
break;
case "approved":
orders = db.Orders.Where(o => o.Status == 1);
break;
case "delivered":
orders = db.Orders.Where(o => o.Status == 2);
break;
default:
orders = db.Orders;
break;
}
return Json(new { data = orders.ToList() }, JsonRequestBehavior.AllowGet);
}
Tag <a> is outside the table:
peding
My Script:
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
},
columns: [
{ data: "CodeOrder"},
{ data: "FullName"},
{ data: "Email"},
{ data: "Phone" },
]
To send data from DataTables to the server (i.e. to your controller), you use the data option of the ajax function. So, first of all, add that:
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function() {
return dataToSend;
}
},
You declare dataToSend as an empty JavaScript object at the start of the document.ready function:
var dataToSend = {};
Here is my simplified version of your <a> tag:
<a id="linkOne" linkData="pending" href="#">submit</a>
Following the dataToSend declaration, I added the following click handler for the <a> tag:
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { "linkData": linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
This code extracts the "pending" text from linkData="pending" in the <a> tag and adds it to the dataToSend object.
Finally, I trigger the DataTable ajax call using reload().
In the controller, this data will be received as a standard URL query parameter (because you are using GET):
linkData=pending
So you can access that in the usual way and format your response accordingly.
In your case, you need to replace my dataToSend logic with your required logic, for your specific <a> tag.
An important point here is that you need to create your dataToSend object correctly.
For one value, it is created as this, as in the above example:
{ "linkData": "pending" }
If you need to send multiple values (e.g. if you are processing a form) then you would build a JavaScript object like this:
[
{
"name": "fieldOne",
"value": "x"
},
{
"name": "fieldTwo",
"value": "y"
}
]
In this case, the object is an array of key-pair values.
For simple forms, the JavaScript serializeArray() function can assist with that - for example:
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
UPDATE
In case it helps, here is the full HTML page for my test code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Personnel</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
<br>
<form id ="formOne">
<input id="fieldOne" type="text" name="fieldOne"></input>
<input id="fieldTwo" type="text" name="fieldTwo"></input>
<input type="submit" value="Submit">
</form>
<br>
<a id="linkOne" linkData="pending" href="#">submit</a>
</div>
<script type="text/javascript">
$(document).ready(function() {
var dataToSend = {};
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { linkData: linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
var table = $('#example').DataTable( {
ajax: {
url: "http://localhost:7000/personnel",
method: "POST",
data: function( ) {
return dataToSend;
},
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "firstname" },
{ "data": "name" },
{ "data": "phone" }
]
} );
} );
</script>
</body>
</html>
Welcome to StackOverflow!
You're already very close and the snippets you provided are helpful. What you're missing is that you want the data to update without leaving the page. Using an anchor tag the way you are will direct you to that page. Also, you controller action is returning a JsonResult, which won't return any type of view (but is correct in this case).
You need to add a page event that triggers on clicking the button and refreshes the data source.
There's a few approaches you can take for this, but here's one of them:
<button class="filter-datatable" data-url="#Url.Action("Index","Cart", new {isvk = "pending" })">
// pageScript.js
// jquery, initialization, etc...
$('.filter-datatable').on('click', function() {
var newSource = $(this).data('url');
datatable.ajax.url(newSource).load();
}
Update Script
$(document).ready(function () {
//test
var dataToSend = {};
$("a#linkOne").on('click', function () {
event.preventDefault();
var linkDataValue = $(this).data('id')
var linkurl = $(this).data('url')
dataToSend = { isvk: linkDataValue };
datatable.ajax.reload();
});
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function () {
return dataToSend;
}
},
columns: [
{ data: "CodeOrder" },
{ data: "FullName" },
{ data: "Email" },
{ data: "Phone" },
],
});
});
tag <a>:
<a id="linkOne" data-id="pending" href="#">submit</a>
Related
I click "ok" and in console error :
I'm new to programming and I need help. I need to use json to form a datatable from several data structures. At this point, I'm stuck on this error. Help please understand
The function in the controller is json.
[HttpGet]
public JsonResult Lowx()
{
var query = db.Infos.
Include(x => x.Profile).
Include(x => x.Cars).
ToList();
return Json(new { data = query });
}
table and ajax
<table class= "table" id="example" >
<thead>
<tr >
<th>first name</th>
<th>last name</th>
<th>middle name</th>
<th>birthday</th>
<th>carname</th>
<th>carnumber</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function (data) {
$("#example").DataTable({
ajax: {
url: '#Url.Action("Lowx")',
type: 'GET',
dataSrc: ""
},
columns: [
{ data: "FirstName", name: "FirstName" },
{ data: "LastName", name: "LastName" },
{ data: "MiddleName", name: "MiddleName" },
{ data: "BirthDate", name: "BirthDate" },
{ data: "CarName", name: "CarName" },
{ data: "CarNumber", name: "CarNumber" }
]
});
Console: Failed to load resource: the server responded with a status of 500 (Internal Server Error).
SCREENSHOTS FOR ALFRED AND ALL)
Screenshot copy-paste
Try copy-pasting this example in your view file. When it works fine, change the url to parse your own data and it should work. Note that the action is a POST, not a GET.
[HttpPost]
public JsonResult Lowx()
{
var query = db.Infos.Include(x => x.Profile).Include(x => x.Cars).ToList();
return Json(new { data = query });
}
http://jsfiddle.net/bababalcksheep/ntcwust8/
$(document).ready(function () {
var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
'type': 'POST',
'url': url,
'data': function (d) {
return JSON.stringify( d );
}
}
});
$('#reload').click(function (e) {
table.ajax.reload();
});
$('.toggleCols').click(function (e) {
e.preventDefault();
var column = table.column( $(this).attr('data-column') );
column.visible( ! column.visible() );
});
});
Please declare the DataTable as follows:
$('#example').DataTable({
"ajax": {
"url": '#Url.Action("Lowx")',
"dataSrc": ""
},
"columns": [
{ "FirstName", "data.Profile.FirstName" },
{ "LastName", "data.Profile.LastName" },
{ "MiddleName", "data.Profile.MiddleName" },
{ "BirthDate", "data.Profile.BirthDate" },
{ "CarName", "data.Cars.CarName" },
{ "CarNumber", "data.Cars.CarNumber" }
]
});
In Chrome, look at the Network tab to see if the Ajax call was formed properly. In Visual Studio, put a Breakppoint at the beginning of Lowx() to see if you reach the code. Please share your findings.
I tried to use reactjs work with C# MVC, and i want to use reactjs ajax to get json array from controller,then show the array elements into select options. But if i use local array, it could show in the select options. I can print out the array element when i use ajax query server method. I do not what happenend.
My view:
<div class="col-md-12">
<div class="col-md-2" id="select">
</div>
</div>
<script type="text/babel">
var Groups = React.createClass({
getInitialState: function () {
return {
data: []
};
},
componentDidMount: function(){
this.serverRequest = $.get(this.props.rout, function(response){
this.setState({
data: response
});
}.bind(this));
},
componentWillUnmount: function(){
this.serverRequest.abort();
},
render () {
return (<select className="selectpicker" multiple="multiple" title="Choose 2-4 colors" data-live-search="true">
{this.state.data.map(function (x) {
console.log(x);
return <ABC value={x} />;
})}
</select>);
}
});
var ABC = React.createClass({
render: function(){
console.log("Option");
console.log(this.props.value);
return <option value={this.props.value}>{this.props.value}</option>;
}
});
ReactDOM.render(
<Groups rout="/CodingManagement/Notification/GroupName" />,
document.getElementById('select')
)
</script>
I could see the console result, but it does not show in view. But if i pass the array to {data}, it could show in the view.
Like this one, it works. I do not know why
<script type="text/babel">
var Groups = React.createClass({
getInitialState: function () {
return {
data: this.props.rout
};
},
render () {
console.log("Groups");
console.log(this.state.data);
return (<select className="selectpicker" multiple="multiple" title="Choose 2-4 colors"
data-live-search="true">
{this.state.data.map(function (x) {
return <ABC value={x}/>;
})}
</select>);
}
});
var ABC = React.createClass({
render: function () {
console.log("Option");
console.log(this.props.value);
return (
<option value={this.props.value}>{this.props.value}</option>
);
}
});
ReactDOM.render(
<Groups rout={["Group4", "Group1", "Group11"]}/>
,
document.getElementById('select')
);
This is server code
public JsonResult GroupName()
{
string[] group = new string[] { "Group4", "Group2", "Group3" };
return Json(group, JsonRequestBehavior.AllowGet);
}
I have problems with memory leaks.
I display a table (with DataTables plugin) in my Html page following a select tag (Select2) that has an event change().
I noticed some memory leaks with the task manager (IE or FireFox).
My code works well, the only problem is memory leaks.
Here is my Html code, I have 2 tables, the second (table_statistic_10_ligne) is displayed when I click on one row of my first table (table_statistic_10), it displays the details of this row :
<body>
<select id="Select2" name="D1" style="margin-right :50px">
</select>
<script>
$("#Select2").change(function () { selectStat10(Select2.options[Select2.selectedIndex].value) });
</script>
<table id="table_statistic_10" class="display">
<caption class="caption">Detail van verkopen</caption>
<thead>
</thead>
<tbody>
</tbody>
</table>
<br />
<br />
<table id="table_statistic_10_ligne" class="display">
<thead>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
fillSlectTagStat10();
</script>
</body>
Here is my javascript code, in the success, I retrieve the values (retrieved from a web service in C#) and I fill them in the datatables :
function getStatistic10(dstart, dend, nam) {
var response;
var allstat10 = [];
if (typeof myTabLigne10 != 'undefined') {
myTabLigne10.fnClearTable();
}
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_10_Entete',
data: { "start": JSON.stringify(dstart), "end": JSON.stringify(dend), "name": JSON.stringify(nam) },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat10[i] = [response.Items[i].Nom, response.Items[i].Date, response.Items[i].Piece, response.Items[i].Tiers, number_format(response.Items[i].AmoutHT, 2, ',', ' '), number_format(response.Items[i].AmountTTC, 2, ',', ' '), response.Items[i].Quantite];
}
if (typeof myTabEntete10 != 'undefined') {
myTabEntete10.fnClearTable();
}
fillDataTableEntete10(allstat10, dstart, dend);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error loading statistic 10");
alert("Status: " + textStatus + "\n" + "Error: " + errorThrown);
}
});
}
Filling dataTables code :
function fillDataTableEntete10(data, dstart, dend) {
if ($("#table_statistic_10").css("visibility") == "hidden")
$("#table_statistic_10").css("visibility", "visible");
myTabEntete10 = $('#table_statistic_10').dataTable({
'aaData': data,
'aoColumns': [
{ "sTitle": "Nom" },
{ "sTitle": "Date" },
{ "sTitle": "Piece" },
{ "sTitle": "Tiers" },
{ "sTitle": "AmoutHT" },
{ "sTitle": "AmountTTC" },
{ "sTitle": "Quantite" }
],
"sPaginationType": "full_numbers",
"iDisplayLength": 10,
"bJQueryUI": true,
"bDestroy": true,
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": false,
"bInfo": false,
"bAutoWidth": false,
"sDom": '<"top"f<"clear">>rt<"bottom"ilp<"clear">>'
});
I have approximately 10 values (customer) in the select tag (Select2). But one customer has about 20.000 rows that I fill in the datatables. And when I selected several times this customer, I see that the memory increases.
I used fnClearTable() but it doesn't work.
Have you an idea because I'm a little lost?
EDIT : I solved the problem, I updtate the DataTables with fnClearTable() and fnAddData(). But now, the problem is with my click event, I have memory leaks because of this code :
myTabEntete10.$('tr').bind('click',function () {
var data = myTabEntete10.fnGetData(this);
$('tr').removeClass('row_selected');
$(this).addClass('row_selected');
loadData10(dstart, dend, data[2], data[3]);
delete data;
});
Why?
I solved the problem.
I replace the DataTables in the existing.
if (typeof myTabEntete10 != 'undefined') {
$('body').off("click", '#table_statistic_10 tbody tr');
myTabEntete10.fnClearTable();
myTabEntete10.fnAddData(allstat10);
} else {
fillDataTableEntete10(allstat10, dstart, dend);
}
And I use the bDeferRenderoption of DataTables, see here.
I'm using this following code for auto complete feature ,
but I need to fetch values from database using sql server 2008 and C# , asp.net.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
How can i fetch that array list values from my database using (EF4 and asp.net)
The first step is to create a C# ASP.Net page which produces a JSON result that the autocomplete plugin can parse. According to the documentation you can use the two following formats:
Array: An array can be used for local data.
There are two supported formats: An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
http://api.jqueryui.com/autocomplete/#option-source
Alternatively you can use a function to parse out whatever format you need but it sounds like the simplest solution will fulfill your needs.
I'm going to assume you're using ASP.Net forms which isn't really tuned for this kind of thing but you can still make it work with some tweaking. Let's create a page in your web application root called SearchResults.aspx.
The first thing to do is to clear out everything from your ASPX file except the line:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SearchResults.aspx.cs" Inherits="ASP.Net_Forms.SearchResults" %>
Then you're free to change the code behind to output whatever format you like. In this case we'll be using JSON in a structure that Autocomplete can understand natively. We'll also need to set the response type.
public partial class SearchResults : System.Web.UI.Page
{
private class SomeSearchableClass
{
public int ID { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
// The autocomplete plugin defaults to using the querystring
// parameter "term". This can be confirmed by stepping through
// the following line of code and viewing the raw querystring.
List<SomeSearchableClass> Results = SomeSearchSource(Request.QueryString["term"]);
Response.ContentType = "application/json;charset=UTF-8";
// Now we need to project our results in a structure that
// the plugin can understand.
var output = (from r in Results
select new { label = r.Name, value = r.ID }).ToList();
// Then we need to convert it to a JSON string
JavaScriptSerializer Serializer = new JavaScriptSerializer();
string JSON = Serializer.Serialize(output);
// And finally write the result to the client.
Response.Write(JSON);
}
List<SomeSearchableClass> SomeSearchSource(string searchParameter)
{
// This is where you'd put your EF code to gather your search
// results. I'm just hard coding these examples as a demonstration.
List<SomeSearchableClass> ret = new List<SomeSearchableClass>();
ret.Add(new SomeSearchableClass() { ID = 1, Name = "Watership Down" });
ret.Add(new SomeSearchableClass() { ID = 2, Name = "Animal Farm" });
ret.Add(new SomeSearchableClass() { ID = 3, Name = "The Plague Dogs" });
ret = ret.Where(x => x.Name.Contains(searchParameter)).ToList();
return ret;
}
}
And finally just change your jQuery to use the correct source:
$( "#tags" ).autocomplete({ source: "/SearchResults.aspx" });
See this below sample from jQueryUI Autocomplete Example
Hope you can do by yourself!.
All you need to do is call some page or handler and prepare JSON data.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "yourpage.aspx",
dataType: "jsonp",
data: {
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
I am trying to make an ajax sending data in JSON from a partial view. I get a System.ArgumentException: Invalid JSON primitive: undefined.
When I evaluate the object in a browser data contains an int and two strings. Can anyone tell me what I am doing wrong?
Partial View
#model FTD.Models.FTDAccountExtended
#using (Html.BeginForm()) {
<fieldset>
<legend>Update Policy Number</legend>
#Html.HiddenFor(m => m.account.ftd_accountsid)
#Html.HiddenFor(m => m.OldPolicyNumber)
#Html.TextBoxFor(m => m.account.ftd_policyno)
<input type="button" value="update" id="update" />
</fieldset>
}
<script type="text/javascript">
$(document).ready(function () {
$("#update").click(function () {
var myUrl = '#Url.Content("~/")' + '/Maintenance/UpdatePolicyNumber';
var data = [{ 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()}];
$.ajax({
url: myUrl,
type: 'POST',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.message);
},
error: function (errMsg) {
alert("Error", errMsg);
}
});
});
});
The controller method is
public ActionResult UpdatePolicyNumber(int ClientNumber, string OldPolicyNumber, string NewPolicyNumber)
{
var message = string.Format("UpdatePolicyNumber CN:{0} OP:{1} NP:{2}", ClientNumber, OldPolicyNumber, NewPolicyNumber);
if (_log.IsDebugEnabled)
_log.Debug(message);
if (!string.IsNullOrEmpty(NewPolicyNumber) && ClientNumber > 0)
{
_entities = new CloseFTD_Entities();
_entities.UpdatePolicyNumber(ClientNumber, OldPolicyNumber, NewPolicyNumber, User.Identity.Name);
}
return Json
(
new
{
message = message
},
JsonRequestBehavior.AllowGet
);
}
I would just try posting the the data as a java script object (as Marc mentioned above)
and remove the content type attribute.
success: function (data) {
alert(data.success);
},
shouldn't this be
success: function (data) {
alert(data.message);
},
Your problem is here
var data = [{ 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()}];
You are building an array - but your controller excepts the direct values, so just remove the [] brackets:
var data = { 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()};
That should work.