How can I call action method from jquery ajax form? I create below code, but parameters in my action method is always null.
Note: I already added all needed scripts, such as quill.js, jquery.unobtrusive-ajax.js
I have this form:
<form data-ajax="true" data-ajax-method="post" method="post">
<input type="text" name="postTitle" class="form-group" />
<div id="postData" name="postData"></div>
<br />
<button type="submit" class="btn btn btn-outline-dark" id="btnCreate">Create post</button>
</form>
and this javascript and jquery scripts:
QUILL:
<script>
var toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['link', 'image', 'video', 'formula'], // add's image support
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'] // remove formatting button
];
var quill = new Quill('#postData', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
</script>
Calling post action method:
$(function () {
$('#btnCreate').click(function () {
var props = [{
"PostTitle": $("postTitle"),
"PostData": quill.root.innerHTML
}]
$.ajax({
url: '#Url.Action("Create", "Post")',
type: "POST",
data: { JSON.stringify(props) },
contentType: "application/json",
dataType: "json",
async: true,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc(e) {
console.log('Error!', e);
}
//console.log(postData);
});
});
My action method:
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreatePost(string props) // here props is null
{
Post post = new Post { PostBody = props };
db.Posts.Add(post);
await db.SaveChangesAsync();
return View();
}
I think that every input element is obtained from val ();
$("postTitle").val() maybe
Related
I am using ASP.NET; I am getting the data from the backend as expected, but it is not showing in the web page using a datatable.
Web page:
#{
ViewBag.Title = "Employee";
}
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
JavaScript portion of code (jQuery)
$(document).ready(function () {
$('#myTable').DataTable({
processing:true,
"ajax": {
"url": "/Employee/GetList",
"type": "GET",
"dataType": "json",
"success": function (msg) {
console.log(msg.data);
},
"failure": function (response) {
alert(response);
},
"error": function (response) {
alert(response);
}
},
"columns": [
{ data: "EmployeeId" },
{ data: "Name" },
{ data: "Age" },
{ data: "Position"},
]
});
});
Here is the response I am getting from the backend. This is the data I copied from Netword -> Response tab against the endpoint I call to fetch the data
{
"data": [
{
"EmployeeId": 1,
"Name": "Dhruv",
"Age": 23,
"Position": "Full Stack Developer"
},
{
"EmployeeId": 2,
"Name": "Soni",
"Age": 21,
"Position": "DBA"
},
{
"EmployeeId": 3,
"Name": "Mike",
"Age": 24,
"Position": "Frontend Developer"
},
{
"EmployeeId": 4,
"Name": "Bob",
"Age": 20,
"Position":"SRE"
}
]
}
I am trying to get the data from database and show it to the user using a datatable. I am successfully getting the response back from the database, but the data is not showing inside the table. And I can't figure it out why....
Update:3
Controller:
public ActionResult GetList()
{
var empList = new List<Employee>()
{
new Employee(){ EmployeeId = 1, Name = "A", Age = 19, Position = "Engineer-I"},
new Employee(){ EmployeeId = 2, Name = "B", Age = 20, Position = "Engineer-II"},
new Employee(){ EmployeeId = 3, Name = "C", Age = 21, Position = "Engineer-I"},
new Employee(){ EmployeeId = 4, Name = "D", Age = 22, Position = "Engineer-III"},
};
return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
}
Note: You even can directly return Json(new { empList }) in that case, in your HTML-Ajax you only have to write return msg; not msg.data
View:
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/DatatableInAnotherWay/GetList",
"dataSrc": function (msg) {
console.log(msg.data);
return msg.data;
}
},
"columns": [
{ "data": "employeeId" },
{ "data": "name" },
{ "data": "age" },
{ "data": "position" },
]
});
});
</script>
}
Note: I am returning as return Json(new { data = empList }); so I would receive response as msg.data. Check the response in your browser console as below:
Importantly, be sure about the column case as you can see I am getting it as lower-case so I bind them as like this"data": "employeeId". As you are saying you are getting in Upper-Case as EmployeeId you should then bind as "data": "EmployeeId"
Final Output:
Special Note:
Remember these words forver, If you want to be a great programmer, you must concentrate on :
Debugging
Code readability
Self reading/teaching attitude
Update:2
If you still want to persist with your code: You could do as following:
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/Employee/GetList",
"dataSrc": function (msg) {
return msg;
}
},
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
});
Issue on your code:
You were defining the column in worng way: you should do it in following way:
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
Update:2 Output:
Update:
Based on your updated question, its clearly seen that you are ajax calling pattern is incorrect. How your msg.data would be bounded into your "columns": no way. Please try my updated code. Just copy and paste.
I am successfully getting the response back from the database but the
data are not showing inside the table. And i can't figure it out why?
It's because of your row definition in your columns within the datatable.
You would define all of your data members in lower case - like
"columns": [
{ data: "employeeId" },
{ data: "name" },
{ data: "age" },
{ data: "position"},
]
Note: UpperCase EmployeeId, Name etc in jQuery datatable are causing parsing issues. In addition, please follow the $.ajax({}); calling format as per my demo for better code readability.
Complete example:
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Employee/GetList",
success: function (response) {
$('#myTable').DataTable({
data: response,
columns: [
{ data: 'EmployeeId' },
{ data: 'Name' },
{ data: 'Age' },
{ data: 'Position' }
]
});
},
error: function (response) {
alert(response.responseText);
}
});
});
</script>
}
Output:
I am getting the following error when trying to load DataTables ajax sourced data:
DataTables warning: table id=report-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Below is my DataTables html:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
Below is my DataTables javascript:
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
Below is the confirmed json my C# controller is returning for the DataTables ajax data:
{
"data":[
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
}
]
}
The error seems to be related to the JSON format, but not sure what is wrong?
EDIT:
Adding full javascript code:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
Your <script> block should look like this to initialize your data for your Data Tables:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
method: "post",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data":data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
the data source should be an array of arrays that contains the data in the tbody
say
data = [
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"]
];
see the example [https://datatables.net/examples/data_sources/js_array.html][1]
additionally, use data: data.data instead of "ajax" : data
As your JSON response is an object but not an array, specify the ajax to get the JsonResponse.data as below:
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": function (json) {
return json.data;
},
},
OR
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": "data"
},
JQuery answer
Updated: Change from json.data to data as Post Owner changed requirement.
data: data
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data": data,
... // Remaining DataTable configurations
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
Output
Reference
ajax - DataTables.net
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 am trying to add a new object to a existing JSON array. This is my JSON array stored in the database.
{
"Id":4,
"UserId":2336276,
"Name":"Data",
"Widgets":[
{
"Id":1,
"Description":"Test1",
"DataSource":"Person1",
"ChartType":"bar",
"x":0,
"y":0,
"width":3,
"height":2
},
{
"Id":2,
"Description":"Test2",
"DataSource":"Person2",
"ChartType":"pie",
"x":3,
"y":0,
"width":3,
"height":2
},
{
"Id":3,
"Description":"Test3",
"DataSource":"Person3",
"ChartType":"heatmap",
"x":6,
"y":0,
"width":3,
"height":2
}
]
}
When I want to add a new widget I want it as a object in this JSON array.
This is my Angular HTTP call:
$scope.addWidget = function () {
var Indata = {
"Id": $scope.widgets.Widgets.length + 1,
"name": $scope.name,
"description": $scope.Widgets.description,
"datasource": $scope.Widgets.datasource,
"charttype": $scope.Widgets.charttype,
"x": $scope.Widgets.x = 0,
"y": $scope.Widgets.y = 0,
"width": $scope.Widgets.width = 3,
"height": $scope.Widgets.height = 2
};
$http({
url: "Dashboard/AddWidget",
method: "POST",
params: Indata
})
$scope.widgets.push(Indata);
};
And this is my HTML page:
<md-dialog>
<form ng-cloak>
<md-toolbar>
<div class="md-toolbar-tools">
<h2>New widget</h2>
<span flex></span>
</div>
</md-toolbar>
<md-input-container>
<label>Name</label>
<input type="text" ng-model="name">
</md-input-container>
<md-dialog-content>
<label>Datasource</label>
<md-select ng-model="datasource"></md-select>
</md-dialog-content>
<md-dialog-content>
<label>Type graph</label>
<md-select ng-model="graphtype"></md-select>
</md-dialog-content>
<md-input-container>
<label>Description</label>
<input type="text" ng-model="description">
</md-input-container>
<md-dialog-actions layout="row">
<md-button id="add" ng-click="addWidget()">
Add widget
</md-button>
<md-button ng-click="hide()">
Cancel
</md-button>
</md-dialog-actions>
</form>
When I click on Addwidget it doesn't add to the JSON array but outside of it as a new object. I am not sure but I think I am doing something wrong with the nested json array.
What am I doing wrong?
Kind regards
UPDATE:
[HttpPost]
public string AddWidget(Dashboard model)
{
var data = _dashboarBusiness.StoreDashboard(model);
return Newtonsoft.Json.JsonConvert.SerializeObject(data);
}
You are not adding it into the json object that you obtained from database.
Suppose
$scope.jsonObj= {
"Id":4,
"UserId":2336276,
"Name":"Data",
"Widgets":[
{
"Id":1,
"Description":"Test1",
"DataSource":"Person1",
"ChartType":"bar",
"x":0,
"y":0,
"width":3,
"height":2
},
{
"Id":2,
"Description":"Test2",
"DataSource":"Person2",
"ChartType":"pie",
"x":3,
"y":0,
"width":3,
"height":2
},
{
"Id":3,
"Description":"Test3",
"DataSource":"Person3",
"ChartType":"heatmap",
"x":6,
"y":0,
"width":3,
"height":2
}
]
}
Then you have to push into the widgets array of this object.
$scope.jsonObj.Widgets.push(Indata);
You may also want to check if your $http is working correctly because I can't see anything being done in the success callback of the request.
$http({
url: "Dashboard/AddWidget",
method: "POST",
params: Indata
}).then(function(data) {
$scope.success = "Widgets added Successfully"
});
For more reference on $http, check https://docs.angularjs.org/api/ng/service/$http
My model defined:
public class RulePageViewModel
{
public List<RuleItem> RuleItemList { get; set; }
public RuleViewModel RuleViewModel { get; set; }
}
My action defined:
public JsonResult Save(RulePageViewModel viewmodel)
I try to post json, viewmodel.RuleItemList.Count > 0, but instance in viewmodel.RuleItemList is null.
If use model bind,how to bind a list in view?
I haven't try to bind model, just use ajax to post json to action. I think it will work, but failed Code:
var s = { "RuleItemList": [{ "RuleGroupId": 1, "RuleGroupName": "", "Keywords": "ajax", "ResponseDescribe": "dadhsa" }], "RuleViewModel": { "RuleGroupId": 14, "RuleList": [{ "RuleId": 567, "SourceId": 125, "KeyValue": "callback", "SourceType": 0 }], "SourceList": [] } };
var ss = JSON.stringify(s);
var json = JSON.parse(ss);
$.ajax({
url: '#Url.Action("Save")',
type: 'POST',
data: json,
dataType: 'json',
success: function(response) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
OK, I solved it:
var json = { "RuleItemList": [{ "RuleGroupId": 1, "RuleGroupName": "", "Keywords": "ajax", "ResponseDescribe": "dadhsa" }], "RuleViewModel": { "RuleGroupId": 14, "RuleList": [{ "RuleId": 567, "SourceId": 125, "KeyValue": "callback", "SourceType": 0 }], "SourceList": [] } };
$.ajax({
url: '#Url.Action("Save")',
type: 'POST',
data: JSON.stringify(json),
dataType: 'json',
contentType: 'application/json',
success: function(response) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
Thanks all!
Generally you should do something like that:
#for(var i = 0;i<Model.RuleItemList.Count;++i)
{
#Html.TextBoxFor(m => m.RuleItemList[i].Name);
}
#Html.EditorFor(m = > m.RuleViewModel.PropertyOne);
#Html.EditorFor(m = > m.RuleViewModel.PropertyTow);
#Html.EditorFor(m = > m.RuleViewModel.PropertyThree);
Which will eventually generate something like that to the html:
<input type="text" name="RuleViewModel.PropertyOne" value="" />
<input type="text" name="RuleViewModel.PropertyTow" value="" />
<input type="text" name="RuleViewModel.PropertyThree" value="" />
Now because you did not place any view code or any code from your RuleItem an RuleViewModel classes that is going to be some problem to specifically answer your question so please post more info but in general you should understand from what i wrote here how to implement such a from that will post the data to your controller action so that the Model Binder will know which properties to bind..
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx