Im binding my Data in View to Controller, so later I could do what I want with the data. In my View, im using dataTable and #Html.EditorForModel() to render my View.
View
<form action="xx" method="POST">
<table id="myTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th></th>
<th>
#Html.DisplayNameFor(model => model.Field1)
</th>
<th>
#Html.DisplayNameFor(model => model.Field2)
</th>
<th>
#Html.DisplayNameFor(model => model.Field3)
</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
#Html.EditorForModel()
}
</tbody>
<tfoot></tfoot>
</table>
<input type="submit" value="submit" />
</form>
Script
$("#myTable").dataTable({
searching: false,
ordering: false,
responsive: true,
"bLengthChange" : false,
"pageLength": 20,
"bStateSave": true
});
Controller
[HttpPost]
public ActionResult MyAction(List<MyModel> MyListModel)
This method works great if the data is no more than 1 page in dataTables. if its more than 1 page, then My Controller either only can receive the List Data of the first page or receive nothing(null)
How should I bind all of my data in DataTables from View to Controller? This binding should include all pages, not only the first one
I'm unsure how you're triggering the update of data, so assuming it's a button the following should work:
$('#your-button').on('click', function(e){
var data = ('#myTable').DataTable().$('input,select,textarea').serialize();
$.ajax({
url: '/MyController/MyAction/',
data: data,
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
});
Edit 1:
As per this answer to How to post data for the whole table using jQuery DataTables, if you're set on using a form use the following:
var table = $('#myTable').DataTable();
$('#myForm').on('submit', function(e){
var form = this;
var params = table.$('input,select,textarea').serializeArray();
$.each(params, function(){
if(!$.contains(document, form[this.name])){
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
});
});
since you don't want any ajax
Use Javascript Source Data, Pass your model to the view, serialize it, and use it as your source
var myData = #Html.Raw(Json.Encode(Model.ListOfData));
//then pass it to the datatable
$('#example').DataTable( {
data: myData,
columns: [
{ title: "col1" },
{ title: "col2" },
etc ...
]
} );
With DataTables, only the current page data exist in the DOM. If you submit the form, only the current page data are being submitted back in the server. One solution to this is submit the data via ajax:
var myTable = $('#myTable').DataTable();
$('#your-form').on('submit', function(e){
e.preventDefault();
//serialize your data
var data = myTable.$('input,select,textarea').serialize();
$.ajax({
url: '#Url.Action('MyAction', 'MyController')',
data: data,
success: function(responseData){
//do whatever you want with the responseData
}
});
});
You need to use the data() method to get the data for the whole table:
$('#your-form').on('submit', function(e){
e.preventDefault();
var table = $('#myTable').DataTable();
var data = table.data();
$.ajax({
url: '/MyController/MyAction/',
type: 'POST',
dataType: 'json',
contentType: "application/json;",
data: JSON.stringify(data),
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
Please go through following link
https://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
Related
I have a page lets say Edit.cshtml in that page is a dropdownlist of item to updated. the loading of that page has no problem, the problem comes when I select an item on the dropdownlist and execute an ajax call.
$('#dDL').kendoDropDownList({
optionLabel: "Select",
dataTextField: "Value",
dataValueField: "Id",
dataSource: {
transport: {
read: '#Url.Action("GetItems", "BulkEdit")',
}
},
change: function (e) {
//this is where i call the '#Url.Action("GetMetaDataDetails", "BulkEdit")'
var test = getMetaDataDetails();
popupwindow.data("kendoWindow").open();
popupwindow.kendoWindow({
width: "600px",
title: "Mapping",
visible: false,
//modal: true,
animation: {
close: {
effects: "fade:out"
}
},
actions: [
"Pin",
"Minimize",
"Maximize",
"Close"
],
}).data("kendoWindow").center().open();
}
});
it goes through the controller with no issue, but it throws error if I return a view. Why?
this is my ajax call:
function getMetaDataDetails() {
return $.ajax({
type: "POST",
url: '#Url.Action("GetMetaDataDetails", "BulkEdit")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ itemTypeID: itemtypeID.toString() }),
dataType: "json",
success: function (data) {
debugger;
var checks = data;
},
error: function (data) {
debugger;
var check = data;
alert(result);
}
});
}
and this is my controller:
[HttpPost]
public virtual ActionResult GetMetaDataDetails(int itemTypeID)
{
var importProperties = GetImportColumnProperties(GetModel(itemTypeID));
var result = JsonConvert.SerializeObject(importProperties, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
ViewData["MetaDataModel"] = importProperties;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is the pop-up window that should be populated after executing the getMetaDataDetails(), itemMetaData should have the values return by getMetaDataDetails()
#(Html.Kendo().Window()
.Name("itemwindow")
.Title("Item Mapping")
//.Modal(true)
.Content(#<text>
<table class="table table-bordered">
<thead>
<tr>
<th>Table Column</th>
<th>Excel Column</th>
</tr>
</thead>
#foreach (var props in itemMetadata.GetType().GetProperties())
{
var label = props.GetCustomAttribute<CanBulkUpdateAttribute>().CanBulkUpdate;
if (label == true)
{
var disp = props.GetCustomAttributes<DisplayPropertyName>();
<tbody>
<tr>
<td class="col-sm-3">
<label>
#disp.First().DisplayName
</label>
</td>
<td class="col-sm-3">
<select kendoDropDownList name="" id="ddlitem_#props.Name" style="width :250px;"></select><br>
</td>
</tr>
</tbody>
}
}
</table>
<button id="uploadAll" onclick="updatetable()" class="btn btn-primary">Update</button>
</text>)
//.Width(420)
.Height(440)
.Visible(false)
)
I need to use the return of GetMetadataDetails as model for my "popupwindow"
Hope you can help me.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'EmployeeService.asmx/GetEmployees',
dataType: 'json',
success: function (data) {
$('#datatable').dataTable({
data: data,
columns: [
{ 'data': 'Id' },
{ 'data': 'userID' },
{ 'data': 'userPassword' },
{ 'data': 'userEmail' },
{ 'data': 'userIsActiv' },
]
});
}
});
});
</script>
<body>
<form id="form1" runat="server" method="post">
<table id="datatable">
<thead>
<tr>
<th>Id</th>
<th>userID</th>
<th>userPassword</th>
<th>userEmail</th>
<th>userIsActiv</th>
</tr>
</thead>
</table>
<div>
</div>
</form>
</body>
I have a Jquery datatable which displays the data fetched from SQL database from Web service EmployeeService.asmx/GetEmployees.
I need to make this datatable to be editable like double click any column in any row, then I can edit the data like the datatable in the following link.
https://editor.datatables.net/examples/inline-editing/simple
How can I make the datatable editable like that so that after the editing the data will be updated correctly to the database?
in a MVC 5 project, the Index page contains 2 partial views. One to enter the search arguments and the other to show the rates (via ajax call). Everything works as expected and the rates view does show the returned data. What happens is that if the user goes to another page, in the same project, then returns, the rates partial view is empty, although the search arguments in the other partial view are still present. Is there a way to persist the rates data?
// This script is in the index page with the 2 partial views
<script>
$(function () {
$('#viewSearch').submit(function () {
if ($(this).valid()) {
$.ajax({
url: '/Home/GetRates',
type: "POST",
cache: true,
dataType: 'html',
data: $("#viewSearch").serialize(),
success: function (data) {
$('#viewRates').html(data);
},
});
}
return false;
});
});
</script>
// This is the viewRates
#model Models.Rate
<table class="table table-bordered input-sm">
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Notes)
</td>
<td>
#Html.DisplayFor(modelItem => item.Daily)
</td>
<td>
#Html.ActionLink("BOOK NOW", "Edit", new { id=item.Id })
</td>
</tr>
}
</table>
// and this is the controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetRates()
{
if (ModelState.IsValid)
{
// code
...
return PartialView("~/Views/Shared/Rates.cshtml", rates);
}
return PartialView("~/Home/Contact.cshtml");
}
if the search results are persisted just reload the partial on document.ready
I'm relatively new to Javascript/JSON and I've been looking really long for an example of how to do this. Currently what I have in my View is
<p>Please enter your email and phone number registered with the account</p>
<table id="Table">
<tr>
<td>Email</td>
<td> <input id = "email" type ="text" name= "email" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td> <input id = "phone" type ="text" name= "phone" /></td>
</tr>
</table>
<input type="button" value="Submit" id="sendMSG">
I'd like to send it to the following controler
public JsonResult SendMessage(SMSTestViewModel model)
{
string email = model.email;
string number = model.phone;
}
What i'd like to do is to write a script to say that when I click the button, to send the information I put in the two textboxes to my viewmodel and then to my controller.
I'd also like to do this while it doesn't referesh the page.
If you can possibly lead me in the right direction, that;d be awesome.
I think I understand what you are looking for. You want to post the form to your SendMessage action result?
This is what you want.
function submit() {
$.ajax({
type: "POST",
url: /SendMessage,
contentType: "application/json",
dataType: "json",
data: { "email" : $("#email").value, "phone" : $("#phone").value },
success: function (data) {
console.log(data);
},
error: console.log("Where's the nearest bar?");
});
}
$("#sendMSG").click(function () {
submit();
});
Sorry, I assumed you were using JQuery.
If you do not want to use JQuery just change the.
$("#phone")
to
document.getElementById("phone")
And here is how to to a POST without JQuery.
How to make an AJAX call without jQuery?
Hope this helps.
Hi I'm working on a table
I cannot atm update the table without the site refreshing.
I need a way to easily
Add a row ,Delete a row, Modify a row in a table's content.
my table is build like this.
{....}
#using (Html.BeginForm())
{
<fieldset>
<legend>ShiftTypes</legend>
<table class="EditableTable" id="EditableTableShiftTypes">
<thead>
<tr>
<th>
#:
</th>
<th>
ShiftName:
</th>
<th>
ShiftCode:
</th>
<th>
Suplement:
</th>
<th>
ExtraSuplement:
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (BPOPortal.Domain.Models.ShiftTypeView type in Model.ShiftTypeList)
{
<tr>
<td>
#type.ID
</td>
<td>
#type.ShiftName
</td>
<td>
#type.Name
</td>
<td>
#type.Supplement
</td>
<td>
#type.OneTimePayment
</td>
<td>
<button>
Delete</button>
</td>
</tr>
}
<tr>
<td>
<label>
</label>
</td>
<td>
#Html.Editor("ShiftName")
</td>
<td>
#Html.Editor("ShiftCode")
</td>
<td>
#Html.Editor("Suplement")
</td>
<td>
#Html.DropDownList("ExtraSuplement", new SelectListItem[] { new SelectListItem() { Text = "yes", Value = "true", Selected = false }, new SelectListItem() { Text = "No", Value = "false", Selected = false } }, "--Choose--")
</td>
<td>
<button id="AddButton">
Add</button>
</td>
</tr>
</tbody>
</table>
<button type="submit" id="Gem">
Save</button>
</fieldset>
{....}
I've Tried to use Ajax in the following way but it refreshes the entire page.
{....}
var ID= 2;
$("#AddButton").click(function(){
var ShiftName= $('#ShiftName').attr('value');
var ShiftCode= $('#ShiftCode').attr('value');
var Suplement= $('#Suplement').attr('value');
var ExtraSuplement= $('#ExtraSuplement').attr('value');
$.ajax({
url: '#Url.Action("AddData", "ShiftTypesConfiguration")',
data: { ID: ID.toString(), ShiftName: $('#ShiftName').attr('value'), ShiftCode: $('#ShiftCode').attr('value'), Suplement: $('#Suplement').attr('value'), ExtraSuplement: $('#ExtraSuplement').attr('value') },
type: 'POST',
// contentType: 'application/json; charset=utf-8;',
dataType: 'json',
success: function (response)
{
function fnClickAddRow() {
$('#EditableTableShiftTypes').dataTable().fnAddData([
response.ID,
response.ShiftName,
response.ShiftCode,
response.Suplement,
response.ExtraSuplement,
"<button>Delete</button>"]); }
}
});
ID++;
});
{....}
</script>
My Method in the Controller that should handle the request.
public JsonResult AddData(string ID, string ShiftName, string ShiftCode, string Suplement, string ExtraSuplement)
{
TableViewModel tableViewModel = new TableViewModel();
tableViewModel.ID = ID;
tableViewModel.ShiftName= ShiftName;
tableViewModel.ShiftCode= ShiftCode;
tableViewModel.Suplement= Suplement;
tableViewModel.ExtraSuplement= ExtraSuplement;
return Json(tableViewModel);
}
However it doesn't seem to work Now I'm asking For Ideas and ways to make this better/easier/Working
Edit:saw a copy past Error
EDIT2: I've now changed it slightly I found that I had a error in how my script was running this is the latest. there are still problems but at least now I can see and describe the error.
this is what I changed the script is now
$("#AddButton").click(function (event) {
event.preventDefault();
var ShiftName = $('#ShiftName').attr('value');
var ShiftCode = $('#ShiftCode').attr('value');
var Suplement = $('#Suplement').attr('value');
var ExtraSuplement = $('#ExtraSuplement').attr('value');
$.ajax({
url: '#Url.Action("AddData", "ShiftTypesConfiguration")',
data: { ID: ID.toString(), ShiftName: ShiftName, ShiftCode: ShiftCode, Suplement: Suplement, ExtraSuplement: ExtraSuplement },
type: 'POST',
// contentType: 'application/json; charset=utf-8;',
dataType: 'json',
success: function (response) {
function fnClickAddRow() {
$('#EditableTableShiftTypes').dataTable().fnAddData([
response.ID,
response.ShiftName,
response.ShiftCode,
response.Suplement,
response.ExtraSuplement,
"<button>Delete</button>"]);
}
}
});
ID++;
});
now with the help of firebug I've seen that the values are back on the page but before I can see them the page is refreshed.
I am not writing in code here, but here is how you should do it.
On Add/Edit/Delete make an ajax call to your action. In your Action implement your operation (Add/Edit/Delete) and depending on operation completed successfully or failed due to some error, return a true/false flag as json.
Then in the success function success: function (response){} of the ajax call, check wether the value returned is a true/false which means success or error.
And then using some jquery you can add a row or delete a row from the table.
Check out these links : http://viralpatel.net/blogs/dynamically-add-remove-rows-in-html-table-using-javascript/