Display sum value from controller in view .net core 6 - model-view-controller

I am new to .net core and I couldn't find how to display sum value from controller in view.
I have code in controller that it will show the item details from item master table and sum of the qty from transactions table as balance qty. But I am stuck to display that sum value in view. May I request your help?
Below is my controller code.
''' var result = _context.ItemMaster.Select(x => x.ItemCode + x.ItemDesc + x.Uom + x.ItemReg + x.Transaction.Select(t => t.BalanceQty).Sum());
return View(await result.ToListAsync());'''

You can use ViewBag to display that sum value in view.
In controller, add :
//var result = ...your sum value
ViewBag.result=result;
return View(await result.ToListAsync());
In the view:
#ViewBag.result

Related

Page views mysql

Codeigniter I want to increase +1 when loading page. but the query does 0
'views + 1' and I did 10 no problem.
It didn't make sense to throw the query for views.
function get_views()
{
$this->db->set('views', 'views+1');
$this->db->where('Id', 1);
$this->db->update('pages'); // gives UPDATE mytable SET field = field+1 WHERE id = 2
}
You need to pass a third parameter as false like below:
$this->db->set('views', 'views+1', FALSE);
The Third Parameter tells CodeIgniter not to protect the generated query with backticks. In your case the final query will be
UPDATE pages SET views = views + 1 WHERE Id = '1';

Lotus Domino: View pagination on web

I read on many forums about how to implement a solution for view pagionation, but I didn't solve it.
I created $$ViewTemplateDefault containing some personalized hotspotbuttons for Next, Previous and a text field $$ViewBody. ( or, alternatively, an embedded view ).
Any tips and help will be really appreciated.
I will explain in a couple words, just to be clear:
So, initially: the first 30 lines will appear => in a right corner: Page 1.
If Next is clicked => the next 30 lines => Page 2. and so on.
Here is a working solution for categorized views too. It calculates the current page number based on the previous page number and uses cookies.
Add to your form a Path-Thru HTML text <span id="pageNumber"></span > for the page number:
and add following code to form's onLoad event as Web/JavaScript:
function getURLParameter(parameter) {
return decodeURIComponent((new RegExp('[?|&]' + parameter + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function compareStart(start1, start2) {
var list1 = start1.split(".");
var list2 = start2.split(".");
for (i=0; i <100; i++) {
var value1 = list1[i];
var value2 = list2[i];
if (value1 == null) {
return value2 == null ? 0 : -1;
} else if (value2 == null) {
return 1;
}
value1 = Math.round(value1);
value2 = Math.round(value2);
if (value1 !== value2) {
return value1 < value2 ? -1 : 1;
}
}
}
var start = getURLParameter("Start");
var page = "1";
if (start == null || start === "1") {
window.name = Math.floor((Math.random()*10000)+1);
start = "1";
} else {
page = getCookie("page" + window.name);
var oldStart = getCookie("start" + window.name);
page = Math.round(page) + compareStart(start, oldStart);
}
document.getElementById('pageNumber').innerHTML = page;
document.cookie = "page" + window.name + "=" + page;
document.cookie = "start" + window.name + "=" + start;
How does it work?
The commands #DbCommand("Domino"; "ViewNextPage") and #DbCommand("Domino"; "ViewPreviousPage") return an URL with parameter "&Start=". This is the row number in view where the current page starts. For categorized views they return a hierarchical number like "&Start=1.2.4.2". That means that the view starts at the first main topic, subtopic 2, subsubtopic 4, document 2.
This parameter "&Start=" gives us the possibility to recognize if user pressed "prev" or "next": we just compare the URL "&Start=" parameter of current and former page.
For that, we have to remember the URL "&Start=" parameter and put it into a cookie "start".
We also need to save the current page number. We put it into a cookie "page".
At onload event we calculate the current page number based on previous page number:
if "&Start=" parameter is larger now then we add 1
if "&Start=" parameter is smaller now then we subtract 1
if "&Start=" parameter didn't change then we keep the former value
If "&Start=" parameter is empty we know we are on page 1.
Here is one other thing we have to deal with: cookies are saved per user session not per browser tab. That means, if we have two views open in browser same cookies "start" and "page" would be used. To avoid that, we have to add to cookie name something tab specific. I use for that a random four digit number and save it in window.name which is tab specific.
I understand your question that you have a working form $$ViewTemplateDefault and now looking for a possibility to show the current page number "Page nn" in that form.
I assume that you use #DbCommand("Domino"; "ViewNextPage") for getting next page and #DbCommand("Domino"; "ViewPreviousPage") for getting previous page.
Those next and prev functions working the way that always one document will "overlap". If you have 30 lines per page and click next, then last document will be first in next page and next 29 show up in addition. You can watch that in used URL parameter "&Start=": 1 ... 30 ... 59 ... 88 ...
Knowing this you can count the current page number this way:
_start := #ToNumber(#Replace(#UrlQueryString("start"); ""; "1"));
_count := #ToNumber(#Replace(#UrlQueryString("count"); ""; "30")) - 1;
#Integer((#ToNumber(_start) / _count) + 1)
Be aware that this will work for non-categorized and non-collapsible views only.
A more sophisticated solution you can find here. It has additional features like GoTo page and Documents per page.
If you have the chance for your project then use XPages instead. You can do pagination much easier as it is available "out of the box".
Update:
You won't find a reasonable solution for categorized views. If you don't want to use Domino Data/Access Services REST API you have to live with the Domino view URL parameters (look here for "OpenView"). You aren't able to tell from "&Start=" or any other parameter on which page you are currently on.
The easiest way to get a good working pagination is using XPages. Hope you are allowed to use it in your project...

C# Entity Framework and Predicate Builder - Find the Index of a Matching Row within an IQueryable / Pagination Issue

I have a PredicateBuilder expression which returns an IQueryable like so (contrived example):
var predicate = PredicateBuilder.True<CoolEntity>();
predicate = predicate.And(x => x.id > 0);
IQueryable<CoolEntity> results = CoolEntityRepository
.FindBy(predicate)
.OrderByDescending(x => x.id);
I then use this to generate a paginated list containing only the results for a given page using an MVC Index controller for CoolEntity entities like so:
int total = results.Count(); //Used by my controller to show the total number of results
int pageNumber = 2;
int pagesize = 20;
//Only get the entities we need for page 2, where there are 20 results per page
List<CoolEntity> resultList = results
.Skip(pageNumber * pageSize)
.Take(pageSize)
.ToList()
This query ensures that only the relevant results are returned for each page, as there are many thousands of records returned from an SQL database via the repository. It has been working nicely.
The problem is, I now want to be able to find out which of the paginated pages for my Index I would need to return for a particular entity. For example, say one of my CoolEntity objects has an ID of 5 - how could I determine what the value for pageNumber would need to be if I wanted to load the paginated page that that entity would be on for my Index controller?
Specifically, how could I find out that for results, the entity with ID 5 was the 651st row, and consequently use this number to determine pageNumber (i.e. Math.Ceiling(651/pagesize) or something similar)? Is there a better approach to this?
A colleague of mine came up with a solution for this which seems to be very fast.
results
.Select( x => x.id)
.ToList()
.Select((entry, index) => new { ID = entry, Rank = index + 1, PageNumer = ((index+ 1) / pagesize ) + 1 })
.Where(x => x.id== 5)
This found the result from ~100000 records in about 00:00.191 seconds when tested in Linqpad. Please let me know if you have a more efficient way of doing this.

How to get the selected row ids sorted according to index in jqgrid?

I'm using
getGridParam('selarrrow');
to get the rows that are selected,where the method returns me the selected row ids according to their selection,but I want the ids according to their index.Do I have to write a method to sort the ids or is there a inbuilt method which returns me the selected row ids in order of their indexes.
thanks in advance
If you mean the index of the row in the grid then you have to resort the array or id returned by $("#gridId").jqGrid("getGridParam", "selarrrow"). You can use sort() method of Array with your custom sort function. You can just use the fact that ids are the ids of <tr> elements. So the DOM elements of <tr> has native implemented rowIndex property which you can get by $("#"+rowid)[0].rowIndex.
In the simplified form the code could be about the following
var selRowIds = $("#gridId").jqGrid("getGridParam", "selarrrow");
selRowIds.sort(function (id1, id2) {
// one can use document.getElementById alternatively
return $("#" + id1)[0].rowIndex - $("#" + id2)[0].rowIndex;
});
or you can use namedItem method instead
var $grid = $("#gridId"),
selRowIds = $grid.jqGrid("getGridParam", "selarrrow"),
rows = $grid[0].rows;
selRowIds.sort(function (id1, id2) {
return rows.namedItem(id1).rowIndex - rows.namedItem(id2).rowIndex;
});
Probably you should include more verification in the code to be sure that the item with id will be found and it has the rowIndex property.

Get IGrouping data in Repeater ItemDataBound

I am wanting to group news articles by year in a repeater. The format would be:
2010
list of articles
2011
List of Articles
My access layer returns a flat list of news articles, specifically List. Therefore, I am grouping them and binding them to the Repeater as follows:
events = DAL.GetEvents();
var groupedNewsList = from e in events
group e by e.StoryDate.Year
into g
select new {
Year = g.Key
, Events = g
};
rptEvents.DataSource = groupedNewsList;
rptEvents.DataBind();
The problem is trying to get the List from within the ItemDataBound event. So far, I have the following:
var data = e.Item.DataItem;
System.Type type = data.GetType();
// getting the year works fine
string year = (string)type.GetProperty("Year").GetValue(data, null).ToString();
// this returns something, but I can't access any properties. I need to get
//access to the contained List<News>
var newsList = type.GetProperty("Events").GetValue(data, null);
Any ideas?
Thanks in advance!
You don't have a List<News> - you just have a grouping. If you want a List<News>, you'll need to change your query, e.g.
var groupedNewsList = from e in events
group e by e.StoryDate.Year into g
select new { Year = g.Key, Events = g.ToList() };
Note that if you're using C# 4 you could do reflection rather more easily using dynamic typing:
dynamic data = e.Item.DataItem;
string year = data.Year.ToString();
List<News> newsList = data.Events;
Alternatively, you could avoid using an anonymous type in the first place - create your own GroupedNewsList type with Year and Events properties, populate that in your query, and then cast to it in your event handler.
The "sender" object in the ItemDataBound event is the repeater -- use it to get to the data-source. If the data-source has been grouped before binding, you can compare the current value to the previous value & hide the year-field if they are equal. Like this:
MyObject item = (MyObject)item.DataItem;
Repeater repeater = (sender as Repeater);
List<MyObject> items = repeater.DataSource as List<MyObject>;
Label lblGrouping = (Label)item.FindControl("lblGrouping");
if (item.ItemIndex == 0 || item.DateField.Year != items[item.ItemIndex - 1].DateField.Year) {
lblGrouping.Text = item.DateField.Year.ToString();
}
This worked for me, as I used a table with each row being one item, and the left-most column contained the "lblGrouping" control.

Resources