Can't display SUM of datatable column from linked table - c#

I am trying to get the sum of a column in a datatable, where the origin of the data is from a different table than the API used by the datatable.
The datatable is using data from a 'Purchases' table, that is related to the 'Handsets' table, in which the 'SalesPoints' data exists, as you can see from the snippet below. I want to get the sum of the SalesPoints column.
<script>
$(document).ready(function () {
var table = $("#purchases").DataTable({
rowReorder: {
selector: 'td:nth-child(2)'
},
ajax: {
url: "/api/purchases",
dataSrc: ""
},
columns: [
{
data: "customer.name"
},
{
data: "handset.name"
},
{
data: "handset.salesPoints"
},
{
data: "datePurchased"
}
],
responsive: true
});
});
To get this sum, I have included the following code in my Controller:
private void ComputeBySalesSalesID(DataSet dataSet)
{
// Presumes a DataTable named "purchases" that has a column named "handset.salesPoints."
DataTable table;
table = dataSet.Tables["purchases"];
// Declare an object variable.
object sumObject;
sumObject = table.Compute("SUM([handset.salesPoints])", "");
ViewBag.TotalValue = sumObject.ToString();
}
To display this sum, I have included '#Html.Label((String)ViewBag.TotalValue)' in my view; when I run the program, this label throws me an exception, saying it cannot be null.
I would seriously appreciate any insight on this as it is preventing me from progressing with a project that is due quite soon. Thanks!
EDIT: View code
#model IEnumerable<SmashingTargets.Models.Purchase>
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Sales</h2>
<p>
#Html.ActionLink("My Profile", "Profiles", "Sales", null, new { #class =
"btn btn-primary" })
</p>
#*Display Sum total*#
<div class="form-group">
#Html.Label((String)ViewBag.TotalValue)
</div>
<table id="purchases" class="table table-striped table-bordered table-hover
table-responsive">
<thead>
<tr>
<th>Customer</th>
<th>Handset</th>
<th>Points Earned</th>
<th>Date Purchased</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Related

Update table in foreach loop with filtered model with Ajax (asp.net mvc c#)

I've developed an asp.net MVC web app where I have a table that shows some items in a model.
I can filter it now with a dropdown list using ajax
The model that i pass to the table is correct (if i go to the model before the foreach there are 3 rows instead of 10 thanks to the filter)
The problem is that the table doesn't change, it always shows all the rows as the initial request.
It look like it works but the table won't update...
There's my jquery ajax call:
$("#Dropdown1Id").on('change', function () {
//console.log("onchange");
//console.log($("#Dropdown1Id").val());
var drpdown1 = $("#Dropdown1Id").val();
var submit = $("#submitButton");
$.ajax({ // crea una chiamata AJAX
data: { data: drpdown1 }, // prendi i dati del form in questo caso del primo dropdown
type: "GET", // GET o POST
url: "/Select/Filter", // li passa al controller
success: function () { // se va con successo esegue il codice seguente
submit.click();
$("#frmId").submit();
},
error: function (error) {
console.log("error")
}
});
});
There's my controller action:
public ActionResult Filter(string data)
{
List<Card> cards = new List<Card>();
ViewBag.stato = new SelectList(myApi.GetState(), "Name", "Name");
if (data != null && data != "")
{
foreach (var card in model)
{
if (card.IdList == data || data == "")
cards.Add(card);
}
return View(cards);
}
return View(model);
}
There's my view with the daple and the dropdown:
#using (Html.BeginForm(new { id = "frmId"}))
{
#Html.AntiForgeryToken()
<table id="tb2">
<tr>
<th>
<h4> LIST : #Html.DropDownList("stato", null, new { #id = "Dropdown1Id" })</h4>
</th>
#*<th>
<h4>ARCHVIED : #Html.DropDownList("closed", null, new { #id = "Dropdown2Id" })</h4>
</th>*#
<th>
<input type="submit" value="Filter" class="btn btn-info" id="submitButton" />
</th>
</tr>
</table>
<br />
<div id="risultato"></div>
<table class="table" id="tb1">
<tr>
<th style="text-align:center">
TRELLO'S CARDS LIST
</th>
<th>LIST</th>
<th>ARCHVIED</th>
<th>Expiration date</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdList)
</td>
#if (item.Closed == "True")
{
<td>YES</td>
}
else
{
<td>NO</td>
}
#if (item.Due != null)
{
<td>
#Html.DisplayFor(modelItem => item.Due)
</td>
}
else
{
<td>
Not Present
</td>
}
</tr>
idList.Add(item.Id);
}
</table>
Let me get you through the execution stack and you'll understand why:
Your MVC view is loaded. When the view is returned to the frontend it is already in Html format. Check Server side rendering here
Basically it means that #foreach (var item in Model) will only execute on the server side and will not re-run when you hit an ajax call. This will only happen on a full post.
While in your page you fire up change dropdown event and the following happens:
An ajax call hit your controller
Data are being returned to the success function
Your success: function () is being executed.
A new form post occurs. See that you didn't do anything with the return data that was returned in the success: function(). You just posted back to the controller
After the post, the full view has returned ignoring any changes in the dropdown and in the data returned.
There are 2 solutions for your problem:
Do a full post and return a new view with the proper data
Write some more javascript to change the DOM inside your sucess function

Rendering HTML Contents according to User Role?

For example: I have to two roles in my application.
1.Administrator // Can perform all CRUD operations on data.
2.Customer // Can only Read the existing data.
In case of returning view to the User according to there role ?
Now I have a choice that create two separate views according to roles.
Let see some Code.
public ActionResult Index()
{
var customers = _dbContext.Customers.Include(c => c.Type).ToList();
if (User.IsInRole(userRole.IsAdministator))
{
return View("Admin_List_View", customers);
} else
{
return View("Customer_ReadOnlyList_View" , customers);
}
}
In the above code.I have two view.
1.Admin_List_View // This view contains all the Data along with Add,Delete,Update,Edit options.
2.Customer_ReadOnly_View // This view will only contains Readonly list.
So my question is that:
In case of simple view i have to follow this approach by writing a separate view for a target roles.
But as it Possible to have a single view and assign the specific section of that to specfic role ?
Note:
I am asking this question is that...In case of complex view that i don't have a choice to create another view from scratch for a particular role. So i am wondering that there is any way to play with the existing view.
For example:
I have to roles.
Admin & customer
and
i have one view.
How to manage that one view for these to roles?
Possible to have a single view and assign the specific section of that to specfic role ?
Yes. You can achieve this with Razor syntax which allows C# in your HTML. Prefix your C# statements with "#". See here.
In your View:
<button>Do Regular User Stuff</button>
#if(User.IsInRole("Admin") {
<button>Do Admin Stuff</button>
}
More Detailed Answer:
public ActionResult Index()
{
var customers = _dbContext.Customers.Include(c => c.Type).ToList();
if (User.IsInRole(userRole.IsAdministator))
{
return View("Admin_List_View", customers);
} else
{
return View("Customer_ReadOnlyList_View" , customers);
}
}
In the above example.
when have two roles and both roles have specfic view.
1.One way is:
to create two view for separate role
for the above example: i had created two views
1.Admin_List_View
2.Customer_ReadOnlyList
2.2nd ways is:
to create sample view and assign html contents based on a user role.
For example:
I have to roles:
again i will say that:
1.AdminList
2.CustomerList.
and now i have only one view:
index.cshtml
index.cshmtl
#model IEnumerable<Vidly.Models.Customer>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 id="heading">Customers</h2>
// This Button is accessible to only admin.
#Html.ActionLink("Add New Customer" , "Add" , "Customer" )
#if (Model.Count() == 0)
{
<p>No Customer is found.</p>
}
else
{
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Full Name</th>
<th>Email Address</th>
<th>Physical Addrses</th>
<th>Type</th>
<th>Actions</th> // This Column will be only accessible to
admin role.
}
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>#item.FullName</td>
<td>#item.EmailAddress</td>
<td>#item.PhysicalAddress</td>
<td>#item.Type.TypeName</td>
// These Button will be only accessible to Admin
// This is the Edit Button.
<td><button data-customer-id="#item.Id" class="btn btn-link js-delete">Edit</button></td>
// This is the Delete Button.
<td><button data-customer-id="#item.Id" class="btn btn-link js-delete">Delete</button></td>
</tr>
</tbody>
}
</table>
}
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#customers").DataTable();
$("#customers").on("click", ".js-delete", function () {
var button = $(this);
var result = confirm("Are you sure you want to delete this customer?");
function (result) {
if (result) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "Delete",
success: function () {
button.parents("tr").remove();
},
error: function (xhr) {
alert("Something goes wrong." + " " + " Error Details " + xhr.status);
}
});
}
});
});
});
</script>
}
So This the entire view.
Now assigning specfic content to specfic Role:
#model IEnumerable<Vidly.Models.Customer>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 id="heading">Customers</h2>
#if(User.IsRole("Admin")) // Checking that if the LoggedIn User is Admin or Not? if The User is Admin Dispay this "Add New Customer Link" Otherwise don't display it.
{
// This Button is accessible to only admin.
#Html.ActionLink("Add New Customer" , "Add" , "Customer" )
}
#if (Model.Count() == 0)
{
<p>No Customer is found.</p>
}
else
{
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Full Name</th>
<th>Email Address</th>
<th>Physical Addrses</th>
<th>Type</th>
#if(User.IsRole("Admin")) // Again Checking That the User is Admin or not? if the User admin Display the table Header otherwise don't display it.
{
<th>Actions</th> // This Column will be only accessible to admin role.
}
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>#item.FullName</td>
<td>#item.EmailAddress</td>
<td>#item.PhysicalAddress</td>
<td>#item.Type.TypeName</td>
#if(User.IsRole("Admin")) // Checking that the LoggedIn User is Admin or Not. If the User is Admin the Display these buttons otherwise don't Display it.
{
// These Button will be only accessible to Admin
// This is the Edit Button.
<td><button data-customer-id="#item.Id" class="btn btn-link
js-delete">Edit</button></td>
// This is the Delete Button.
<td><button data-customer-id="#item.Id" class="btn btn-link
js-delete">Delete</button></td>
}
</tr>
</tbody>
}
</table>
}
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#customers").DataTable();
$("#customers").on("click", ".js-delete", function () {
var button = $(this);
var result = confirm("Are you sure you want to delete this customer?");
function (result) {
if (result) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "Delete",
success: function () {
button.parents("tr").remove();
},
error: function (xhr) {
alert("Something goes wrong." + " " + " Error Details " + xhr.status);
}
});
}
});
});
});
</script>
}

asp.net mvc knockout do not work

I am trying to launch knockout example in ASP.NET MVC but it does not work.
In result i see only
Passenger name Meal Surcharge
knockout part not available. Why? How to fix this?
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-3.4.0.js"></script>
<h2>Index</h2>
<script>
// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}
// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
var self = this;
// Non-editable catalog data - would come from the server
self.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
// Editable data
self.seats = ko.observableArray([
new SeatReservation("Steve", self.availableMeals[0]),
new SeatReservation("Bert", self.availableMeals[0])
]);
}
ko.applyBindings(new ReservationsViewModel());
</script>
<table>
<thead>
<tr>
<th>Passenger name</th>
<th>Meal</th>
<th>Surcharge</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: meal().mealName"></td>
<td data-bind="text: meal().price"></td>
</tr>
</tbody>
</table>
By the time you call ko.applyBindings the whole DOM should be ready.
So you need to move your script block after your table (or more preferable to the bottom of your HTML):
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-3.4.0.js"></script>
<h2>Index</h2>
<table>
...
</table>
<script>
...
ko.applyBindings(new ReservationsViewModel());
</script>
From the documentation:
To activate Knockout, add the following line to a <script> block:
ko.applyBindings(myViewModel);
You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery’s $ function.

Hidden field id is not showing correcly in second page

I am a beginner in jQuery dataTable, last day I implement dataTable 1.10 in my website.
I try to popup the id field in alert window in the selected row.
The first page is works correctly but when I go to the second page I click the
row id is 11. but popup is showing the id of the clicked row is 1.
All pages are showing this error, it's only working correctly in first page.
Please see my code below.
Script
$(document).ready(function () {
//$("#tblProvider").dataTable().destroy();
$("#tblProvider").dataTable({
bProcessing: true,
bPaginate: true,
bLengthChange: false,
bSort: true,
sAjaxSource: '#Url.Action("JsonGetAllTariffPosition", "Admin")',
aoColumns: [
{ sTitle: "Id", bVisible: true, bSortable: false },
{ sTitle: "Number", bSortable: false },
{
sTitle: "Action",
bSortable: false,
mRender: function (o) { return '<i class="ui-tooltip fa fa-pencil" data-toggle="modal" style="font-size: 22px;" data-original-title="Edit"></i><i class="ui-tooltip fa fa-trash-o" style="font-size: 22px;" data-original-title="Delete"></i>'; }
}
],
});
$("#tblProvider").on('click', 'tr td i[class="ui-tooltip fa fa-pencil"]', function () {
var row_index = $(this).closest('td').parent()[0].sectionRowIndex //you need to determine this how ever you like
var table = $('#tblProvider').DataTable()
var column_data = table.row(row_index).data()[0];
alert(column_data);
});
});
Html
<table id="tblProvider"
class="table table-striped table-bordered table-hover table-highlight table-checkable"
data-search="true"
data-paginate="true">
<thead>
<tr>
<th>Id</th>
<th>Tariff Position</th>
#*<th>General Tax</th>
<th>Consumption Tax</th>*#
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Replace the code in your click handler with this
var node = $(this).closest('tr')
var table = $('#tblProvider').DataTable()
var column_data = table.row(node).data()[0];

Using jQuery to post back to Controller

In my web page, I have a series of tables that basically just contain rows of information. Each of these is given an id in a for loop and I'm trying to reference them from outside that. I added classes to both the table and a 'Save Changes' button.
Essentially, my goal is for the user to be able to drag and drop rows around, thereby changing the order. Then they can click the 'Save Changes' button and this will post back to the server with the relevant information.
I am having trouble matching up the button to the relevant table and thereby submitting the id's of each row back to the server in an array. I have written the code to be able to be able to get the ids from each of the tables and their current order, but I don't know how to assign this to an array from within the button click jQuery.
Here is the View:
#foreach (var collection in Model.Collections)
{
<h2>#collection.Season</h2>
#Html.ActionLink("Delete Collection", "DeleteCollection", new { controller = "Edit", brand = collection.Brand.Name, season = collection.Season })
#Html.ActionLink("Edit Collection", "EditCollection", new { controller = "Edit", brand = collection.Brand.Name, season = collection.Season })
#Html.ActionLink("Add Image", "CreateImages", new { controller = "Edit", season = collection.Season })
<p>
To change the ordering of images, drag and drop to your desired position and then click the Save Changes button on the appropriate collection.
</p>
<table class="table-collection" id="table-#collection.Id">
<tr class="nodrop nodrag">
<th>
Id
</th>
<th>
Description
</th>
<th>
Image
</th>
<th>
Options
</th>
</tr>
#foreach (var image in collection.Images)
{
<tr id="#collection.Id-#image.Id">
<td class="dragHandle showDragHandle">
#image.Id
</td>
<td>
#image.Description
</td>
<td>
<img src="#Url.Content("~/" + image.Location)" alt="#image.Description" />
</td>
<td>
<ul>
<li>
#Html.ActionLink("Edit", "EditImage", new { controller = "Edit", brand = image.Collection.Brand.Name,
season = image.Collection.Season, imageId = #image.Id } )
</li>
<li>
#Html.ActionLink("Delete", "DeleteImage", new
{
controller = "Edit",
brand = image.Collection.Brand.Name,
season = image.Collection.Season,
imageId = #image.Id
})
</li>
</ul>
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Save Changes" class="save-order" id="saveTable-#collection.Id"/>
</p>
}
Here is the jQuery so far:
$(document).ready(function () {
$(".table-collection").tableDnD();
$(".save-order").click(function (e) {
e.preventDefault();
$.ajax({ url: window.location.href,
type: 'POST',
data: { ids: $("--ASSIGN ARRAY HERE--"
});
The jQuery to iterate through each row is essentially this:
function(table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Row dropped was "+row.id+". New order: ";
for (var i=0; i<rows.length; i++) {
debugStr += rows[i].id+" ";
}
I see you are using input type submit which is exclusively used to postback forms. What you need to do is wrap every table up in a form with something like this:
#using(Html.BeginForm("Action", "Controller", new{ collectionId = collection.Id }))
{
<input type="submit" value="Save Changes" class="save-order" />
}
Note that this will cause a 'post-back' of the form to Action, Controller. Specify the collection id inside the route values to identify the specific collection.
Do note, you need to add input type hidden with the id's value otherwise the ids' won't get serialised - all you have to specify is the name attribute
<td class="dragHandle showDragHandle">
<input type="hidden" name="ids" value="#(image.Id)" />
#image.Id
</td>
Then you can intercept the call then do it via ajax with:
$(".save-order").click(function(e) {
e.preventDefault();
var form = $(this).closest('form');
if(form.validate()) {
$.post(form.attr('action'), form.serialize(), function() {
alert('The new image order has been saved.');
});
}
return false;
});
The accepting controller action method will probably have this signature
public ActionResult Action(int collectionId, int[] ids)
{
//Do stuff here
return Request.IsAjaxRequest() ? null : View();
}
Now it should support graceful degradation if javascript is disabled (does a normal form submit, otherwise does it via ajax)
Hope this helps :)
You can grab all of the IDs with something like this:
var IDs = [];
$("#mydiv").find("span").each(function(){ IDs.push(this.id); });
In your scenerio, do something like this:
$(document).ready(function ()
{
$(".table-collection").tableDnD();
$(".save-order").click(function (e)
{
var IDs = [];
$("#yourtable").find("draggable-tr-class").each(function(){ IDs.push(this.id); });
e.preventDefault();
$.ajax(
{
url: window.location.href,
type: 'POST',
data: { ids: IDs }
);
}
})
i have been create demo in jsfiddle using json
http://jsfiddle.net/viyancs/4ffb3/11/
if you use like that demo in your server must be get parameter `JSONFile' after that parse this json for what do you want.actually the demo not same with your case but i think you can use this by your logic.

Categories