Setting static property as Session for getting unique results - c#

I have a static property like following:
public static List<string> _pr { get; set; }
Let's imagine a scenario like this:
User 1 logs in and fills the _pr property with 100 string items inside _pr;
User 2 logs in at the same time and does the exact same thing as User one, only this time he gets 250 different string results into _pr!
These results are not from DB, but rather from an API;
How do I ensure the integrity and uniqueness of data so that each user gets displayed only the results that he gets, since I declared only 1 static property and I have multiple users adding different items into it...
Can you guys help me out with this?
How would I solve this properly in c#?
Edit: This is how I add the items to the specific list:
foreach (var item in _pr)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(item);
ResultItem rezultat = new ResultItem();
ViewBag.jsonobjekat = JObject.Parse(JsonConvert.SerializeXmlNode(doc));
rezultat.SaleNumber = ViewBag.jsonobjekat["GetItemTransactionsResponse"]["ReturnedTransactionCountActual"];
rezultat.StoreName = ViewBag.jsonobjekat["GetItemTransactionsResponse"]["Item"]["Seller"]["UserID"];
rezultat.Feedback = ViewBag.jsonobjekat["GetItemTransactionsResponse"]["Item"]["Seller"]["FeedbackScore"];
rezultat.SaleEarning = Convert.ToDouble(ViewBag.jsonobjekat["GetItemTransactionsResponse"]["Item"]["SellingStatus"]["CurrentPrice"]["#text"]) * Convert.ToInt32(rezultat.SaleNumber);
rezultat.SalePrice = Convert.ToDouble(ViewBag.jsonobjekat["GetItemTransactionsResponse"]["Item"]["SellingStatus"]["CurrentPrice"]["#text"]);
rezultat.Title = ViewBag.jsonobjekat["GetItemTransactionsResponse"]["Item"]["Title"];
rezultat.URL = ViewBag.jsonobjekat["GetItemTransactionsResponse"]["Item"]["viewItemURL"];
rezultat.ID = ViewBag.jsonobjekat["GetItemTransactionsResponse"]["Item"]["ItemID"];
lista.Add(rezultat);
ViewBag.jsonba = ViewBag.jsonobjekat;
}
JArray v = JArray.Parse(JsonConvert.SerializeObject(lista).ToString());
ViewBag.rezultati = v; // this is the part where I need to have unique results for each user
And this is how I display the results :
<tbody>
#foreach (var item in ViewBag.rezultati)
{
<tr>
<td>#item.StoreName</td>
<td><button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="" value="#item.StoreName" data-original-title="Analyze competitor"><i class="fa fa-bar-chart-o"></i></button></td>
<td>
<b>
#item.SaleNumber
</b>
</td>
<td><b>#item.Feedback</b></td>
</tr>
}
</tbody>

Related

Display the saved values of in separate dropdown list

I have a dropdownlist in edit view that has a value from the database. What I want to do is to display the saved value in separate dropdown list. For example, I have saved two different data in database with same foreign key to determine that these two records are treated as one. (See below sample image)
https://imgur.com/ex57YTO
I am only using single-selection dropdown list and I am only looping the count of records to determine how many dropdown list to display in the edit page. So if I have "No harm event" and "Complaints" events, this must be displayed in separate dropdown list because what I did now is they are both displaying in one dropdown list so the result is it looks like the record is duplicated (see image below) but actually these two records are in each of the dropdown list.
https://imgur.com/YlVZHWx
https://imgur.com/FXYO4Tn
VIEW
//for loop to count records that will determine how many dropdown list to be displayed
#for (var i = 0; i < Model.SavedEventsToList.Where(a => a.incidentReportId == Model.IRId).Count(); i++)
{
<tr>
<td style="border-bottom:none !important;border-top:none !important;">
<div class="input-group">
<select class="form-control pseEventDDLInEdit" id="pseEventListInEdit" name="pseAddedEvent">
#{
foreach (var item in Model.SavedEventsToList)
{
if (item.selected == "yes")
{
if (item.incidentReportId == Model.IRId) //this is the foreign key that determine these two records are as one
{
<option value=#item.pseEventsId selected>#item.pseEventsName</option>
}
}
else
{
<option value=#item.pseEventsId>#item.pseEventsName</option>
}
}
}
</select>
</div>
</td>
</tr>
}
CONTROLLER
public ActionResult Edit(Guid? id)
{
IMRBusinessLogic imrLogic = new IMRBusinessLogic();
var imrRepo = new IMRRepository();
IMRDTO imr = imrRepo.GetIRDetailsForEdit(id);
imr.SavedEventsToList = imrLogic.SavedEvents(id);
return View(imr);
}
public List<PSESavedEventsDTO> SavedEvents(Guid? incidentReportId)
{
using (IREntities db = new IREntities())
{
var events = (from a in db.SavedPatientSafetyEvents(incidentReportId)
select new PSESavedEventsDTO
{
pseSavedEventId = a.pse_saved_event_category_and_subcategory_id,
pseEventsId = a.pse_events_id,
pseEventsName = a.pse_events_name,
seqNum = a.seq_num,
incidentReportId = a.incident_report_id,
savedRowIndex = a.saved_row_index,
selected = a.selected
}).ToList();
return events;
}
}
I need to separate them so the user can still have an option to edit each of these two records.
This is the expected output I need: https://imgur.com/uwVjvkz
Can someone help me with this.
Thank you in advance.
I already found the solution in this. I just use foreach instead of for loop, and I get the desired output I need.
#foreach (var index in Model.SavedEventsToList.Where(a => a.savedRowIndex != 0))
{
<tr>
<td style="border-bottom:none !important;border-top:none !important;">
<div class="input-group">
<select class="form-control pseEventDDLInEdit" id="pseEventListInEdit" name="pseAddedEvent">
#{
foreach (var item in Model.SavedEventsToList)
{
if (item.selected == "yes")
{
if (item.incidentReportId == Model.IRId && item.savedRowIndex == index.savedRowIndex)
{
<option value=#item.pseEventsId selected>#item.pseEventsName</option>
}
}
else
{
<option value=#item.pseEventsId>#item.pseEventsName</option>
}
}
}
</select>
<span title="Patient Safety Events Description" class="input-group-addon" data-toggle="popover" data-container="body" data-placement="right" data-trigger="hover" data-html="true" href="#" id="login"><i class="fa fa-info-circle"></i></span>
</div>
</td>
</tr>
}

Loop through numbered properties to generate inputs in Razor Pages

I have a model with 34 numbered properties in it as shown below
Public Class ViewModel
{
public string RatingCategory01 { get; set; }
public string RatingCategory02 { get; set; }
public string RatingCategory03 { get; set; }
//...and so on until category #34
}
Rather than code an input for each category in Razor Pages, I would like to use a loop to iterate through all the categories and generate the appropriate control groups. I have tried the code below:
<tbody>
#for (var i = 1; i < 35; i++)
{
string n;
#if (i > 0 && i < 10)
{
n = "RatingCategory0" + i.ToString();
}
else
{
n = "RatingCateogry" + i.ToString();
}
<tr>
<td>
<label asp-for="#string.Format("RatingCategory" + n)" class="control-label"></label>
</td>
<td>
<select asp-for="#string.Format("RatingCategory" + n)" asp-items="Model.CategoryRatingSelectList">
<option value="">Select</option>
</select>
</td>
<td>
<input asp-for="#string.Format("RemedialTime" + n)" class="form-control" />
</td>
</tr>
}
</tbody>
When I build the project and navigate to the page, I get this error:
InvalidOperationException: Templates can be used only with field
access, property access, single-dimension array index, or
single-parameter custom indexer expressions.
I'm not sure if I am on the right track here. I would really like to create a loop to generate these inputs so make future maintenance and changes easier. It's probably pretty obvious from my code/question that I am pretty new to this, so any help is appreciated.
EDIT TO ADD SOLUTION:
I used the solution provided by Ed Plunkett which I have checked below. I altered it a bit and ended up creating a new class called 'Rating' because I found that in practice I needed a more complex object. Inside my view is now
public List<Rating> Ratings = { get; set; }
In the controller, I use a loop to add as many empty ratings as I need to the list depending on the number I need.
for (var i = 0; i < 34; i++)
{
vm.Ratings.Add(new Rating());
}
Though this will likely be updated to use something other than a hard-coded number as the application evolves.
Finally, I used a loop in the view to create a group of controls for every Rating in my List. In this case it is a TableRow containing different controls in different columns:
#for (var i = 0; i < Model.Ratings.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model.Ratings[i].Category)
</td>
<td>
<div class="form-group">
<select asp-for="Ratings[i].RatingValue" asp-items="Model.CategoryRatingSelectList">
<option value="">Select</option>
</select>
</div>
</td>
<td>
<input asp-for="Ratings[i].RemediationMinutes" class="form-control" />
</td>
</tr>
}
I've found that the data in this group of inputs can be bound as a List by simply including
List<Rating> Ratings
in the parameters on whichever method runs when the form is submitted.
This is what you want instead of those 34 properties and their implied 34 RemedialTime siblings:
public List<String> RatingCategory { get; set; } = new List<String>();
public List<String> RemedialTime { get; set; } = new List<String>();
If you have 34 of something and the names differ only by an index number, that's a collection, not 34 distinct properties with sequentially numbered names. Then you can enumerate the 34 items with a foreach loop, or index them individually as RatingCategory[0] through RatingCategory[33]. In C#, collection indexes start at zero, so the first one is 0 and the thirty-fourth one is 33. You get used to it.
You should also look up what String.Format() does. String.Format("Foo" + 1) is exactly the same as "Foo" + 1.
You could convert your model class to dictionary;
var viewModel = new ViewModel()
{
RatingCategory01 = "a",
RatingCategory02 = "b",
RatingCategory03 = "c"
};
var dictionaryModel = viewModel.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(viewModel, null));
Then you can iterate the dictionary in the view.

FOREACH within a FOREACH in MVC

I have the following in a controller :
outputmodel.Add(new SP_RESULTS.RS_Plans()
{
id = Convert.ToDecimal(SPOutput["id"]),
name = Convert.ToString(SPOutput["name"]),
code = Convert.ToString(SPOutput["code"]),
from = Convert.ToDateTime(SPOutput["from"]),
to = Convert.ToDateTime(SPOutput["to"]),
days = Convert.ToDecimal(SPOutput["days"]),
type_id = convert.YoString(SPOutput["type_id"]),
package = Convert.ToString(SPOutput["package"]),
day = Convert.ToDecimal(SPOutput["day"]),
charge = SPOutput["charge"] as decimal?,
type = Convert.ToString(SPOutput["type"]),
percentage= SPOutput["percentage"] as decimal?,
taxes = Convert.ToDecimal(SPOutput["taxes"]),
order = Convert.ToDecimal(SPOutput["order"]),
level = SPOutput["level"] as decimal?,
Column15 = Convert.ToDecimal(SPOutput[15]),
type_order = (SPOutput["type_order"]) as decimal?,
adults = SPOutput["adults"] as decimal?,
});
var order = outputmodel.OrderBy(c => c.from);
ViewData["RS_Output"] = order;
grabbing output from an MS SQL stored procedure and storing in a viewdata (ordered by the FROM date).
My HTML has the following line to start to build the table
#foreach (var item in ViewData["RS_Output"] as Enumerable<app.Models.SP_RESULTS.RS_Plans>)
{
//basic <tr> <td> </td> </tr> table setup, using #item.variablename to pull info from the viewdata.
}
The output I am trying to achieve is for every TYPE under CODE, where the from date => current date, list the room type /package name etc.
and the output I am getting is
what I am trying to get is
What I think I need is a foreach after the current foreach, but I cannot for the life of me figure it out in my head.
I've changed the
var order line in my controller to now read
var order = outputmodel.OrderBy(c => c.rate);
..and I've put the HTML table create code in an if loop
#foreach (var item in ViewData["RS_Output"] as Enumerable<app.Models.SP_RESULTS.RS_Plans>)
{
if (item.to >= DateTime.now)
{
//basic <tr> <td> </td> </tr> table setup, using #item.variablename to pull info from the viewdata.
}
}
.. but, as I say, I am stumped.
I think I need another foreach within the newly created if loop, but I cannot figure out how.
#foreach (var item in ViewData["RS_Output"] as Enumerable<app.Models.SP_RESULTS.RS_Plans>)
{
if (item.to >= DateTime.now)
{
//other table headers/data
<tr>
<td>
#item.type
</td>
</tr>
<tr>
<td>
Room Type
</td>
<td>
Package / Service
</td>
<td>
Availablility
</td>
<td>
Charge
</td>
<td>
PAX
</td>
<td>
Level
</td>
</tr>
<tr>
==> #foreach (subitem = item.type)
==> {
==> foreach (item.type)
==> {
<td>
#item.type_id
</td>
<td>
#item.package
</td>
<td>
#item.Column15
</td>
<td>
#item.charge
</td>
<td>
#item.adults
</td>
<td>
#item.level
</td>
==> }
==> }
</tr>
}
}
can someone please advise?
thanks
UPDATE:
Hi, what I found worked was, if I create a variable called string previous_type =" " , and another called  decimal previous_id =0 ,  then, in the view, I can amend with
if (item.to >= item.checkdate)
{
if ((previous_id != item.id) && (previous_type != item.type.ToString()) )
{
//some more code
if (item.type.ToString().Equals(previous_type) == false)
{
previous_type = item.type.ToString();
previous_date_from = item.date_from;
}
//etc
}
Thanks everyone for their help
OK, I think what you want is to first group the data, then show a table which then shows 'sub-tables' for each type of accomodation?
if so, then yes you can do this with nested foreach loops, but you'd still be better off strongly typing your view and doing the grouping stuff in the controller (or possibly better in some sort of service layer so it can be more easily tested/re-used)... but to get you started, something like this:
Models:
//Raw data
public class DataRowModel
{
public int Id { get; set; }
public string Class{ get;set;}
public string Description { get; set; }
public DateTime BookingDate { get; set; }
}
//Grouped data
public class GroupedDataRowModel
{
public string Class { get; set; }
public IEnumerable<DataRowModel> Rows { get; set; }
}
//View model
public class DataRowsViewModel
{
public IEnumerable<GroupedDataRowModel> Results { get; set; }
}
Controller Action:
public ActionResult TestData()
{
var PretendDatabaseCall = new List<DataRowModel>
{
new DataRowModel{
Id =1,
BookingDate =new DateTime(2017,1,1),
Description ="Booking 1",
Class="Room"
},
new DataRowModel{
Id =2,
BookingDate =new DateTime(2017,2,1),
Description ="Booking 2",
Class="Room"
},
new DataRowModel{
Id =3,
BookingDate =new DateTime(2017,3,1),
Description ="Booking 3",
Class="Suite"
},
new DataRowModel{
Id =4,
BookingDate =new DateTime(2017,4,1),
Description ="Booking 4",
Class="Room"
},
};
//We can now get the data from the database. We want to group by class so we can
//get a summary of items by class rather than a big flat list. Most LINQ to SQL implementations
//(e.g. Entity Framework) when working with Raw entities could convert this to SQL so the SQL server
//does the grouping, but if not it can happen in memory (get all records, then standard LINQ does it on
//the complete list)
var dataGroupedByClass = PretendDatabaseCall
//Minor Edit: apply filtering here not in the view!
.Where(x=>x.BookingDate >= Datetime.Now)
//Group by class.
.GroupBy(x => x.Class)
//for each class, get the records.
.Select(grpItem => new GroupedDataRowModel()
{
//'key' is the thing grouped by (class)
Class = grpItem.Key,
//grpItem has all the rows within it accessible still.
Rows = grpItem.Select(thisRow => thisRow)
});
var model = new DataRowsViewModel
{
Results = dataGroupedByClass
};
return View("~/Views/Home/TestData.cshtml", model);
}
And View:
#* Strongly typed view. saves any casting back and forth.*#
#model SimpleWeb.Models.DataRowsViewModel
#{
ViewBag.Title = "TestData";
}
<h2>TestData</h2>
<table>
<thead></thead>
<tbody>
#foreach (var groupEntry in Model.Results)
{
#*Add single row with just the class...*#
<tr><td>#groupEntry.Class</td></tr>
#*Header row for each class of booking*#
<tr>
<td>Id</td>
<td>Description</td>
<td>Date</td>
</tr>
foreach (var row in groupEntry.Rows)
{
#*add new row for each actual row*#
<tr>
<td>
#row.Id
</td>
<td>
#row.Description
</td>
<td>
#row.BookingDate
</td>
</tr>
}
}
</tbody>
</table>
This produces Data like I think you want:
Room
Id Description Date
1 Booking 1 01/01/2017 00:00:00
2 Booking 2 01/02/2017 00:00:00
4 Booking 4 01/04/2017 00:00:00
Suite
Id Description Date
3 Booking 3 01/03/2017 00:00:00
Obviously you want the 'Room' and 'Suite' parts to contain more information, but this should hopefully help get you started?

Refactor the loop to merge one property when other properties are identical in ASP.net MVC Razor

I have a dataset that currently produces an output as follows:
Code:
Part 1: The View -
#foreach (var dt in Model.PlaceList) {
<tr class="Gap">
<td>
<div class="col-sm-12">
<h3>#dt.PlaceName</h3><br />
<span>#dt.OpenTimings</span><br />
<span>#dt.Slot</span><br />
<span>#dt.ActivityName</span><br />
<span>#dt.Address</span><br />
</div>
</td>
</tr>
}
Part 2: Data Retrieval from DB
var gPlaceList = (from l in _appdb.GetPlaceDetails
select new GetListPlaces {
PlaceName = l.PlaceName,
OpenTimings = l.OpenTimings,
Slot = l.Slot,
Activity = l.Activity,
Address = l.Address
}).ToList();
Part 3: Data structure used to populate the entries
public partial class GetListPlaces {
public string PlaceName { get; set; }
public string OpenTimings { get; set; }
public string Slot { get; set; }
public string Activity { get; set; }
public string Address { get; set; }
}
When looking at the result of output for one Place, we get groups of data that looke like so:
Current Output:
Place Name
Open Timings
Slot1
Activity
Address
Place Name
Open Timings
Slot2
Activity
Address
Place Name
Open Timings
Slot3
Activity
Address
Place Name
Open Timings
Slot4
Activity
Address
Place Name
Open Timings
Slot5
Activity
Address
We want to merge the result to look like this, for all results where the other 4 columns match.
Expected Output:
Place Name
Open Timings
Slot1, Slot2, Slot3, Slot4, Slot5
Activity
Address
The data here is just a sample. the real output in our website has thousands of results and merging the data like this will help us in reducing the display area as well as reduce duplication of data.
Group your data and show it comma separated using string extension method 'Join'
#foreach (var dt in Model.PlaceList.GroupBy(x=> new { x.PlaceName, x.OpenTimings, x.ActivityName, x.Address }))
{
<tr class="Gap">
<td>
<div class="col-sm-12">
<h3>#dt.Key.PlaceName</h3><br />
<span>#dt.Key.OpenTimings</span><br />
<span>#string.Join(",", dt.ToList().Select(x=>x.SlotNo))</span><br />
<span>#dt.Key.ActivityName</span><br />
<span>#dt.Key.Address</span><br />
</div>
</td>
</tr>
}
Use grouping! Just group records by the values that you expect to be same, and use Select to form a new record:
Model.PlaceList
.GroupBy(x => {x.PlaceName, x.OpenTimings, x.ActivityName, x.Address})
.Select(group => new
{
PlaceName = group.Key.PlaceName,
OpenTimings = group.Key.OpenTimings,
...,
Slots = String.Join(", ", group.Select(x => x.SlotNo))
})
Now one record will contain exactly the kind information you needed, and you can loop over the results of this query to output the view.

C# MVC ViewBag error

I'm new to C# MVC so please be patient. I'm having some trouble displaying output for the ViewBag. The application is a Fantasy Football webpage so I have three tables (right now, more to come) one for the basic player info (dbo.Player), one for player background (dbo.PlayerBackground), and one is just a definition table for the team (dbo.Team).
In one of my pages I have a name search and search by position and want to return information across these three tables.
public ActionResult Index()
{
var players = (from p in db.Players
join pb in db.PlayerBackgrounds on p.playerId equals pb.playerID
join t in db.Teams on p.teamAbbre equals t.teamAbbre
select new { playerID = p.playerId, playerName = p.name, position = p.position,
height = pb.height, weight = pb.weight, college = pb.college, dob = pb.dob,
imageUrl = pb.imageUrl, years = pb.years,
teamName = t.name
}).ToList();
ViewBag.data = players;
return View();
}
The query works fine but in index.cshtml I keep getting errors.
#foreach (var player in ViewBag.data)
{
<tr class="success ui-dragable playerRow" style="display: none;">
<td>
<input type="checkbox" />
</td>
<td>
#Html.ActionLink( (string)player.playerName, "Details", new { id = player.playerID }, new { #class = "detailsLink" })
</td>
<td>
#player.teamName
</td>
<td>
#player.position
</td>....
From the research I've done, this seems like it should work. I've tried it both with and without the (string) cast. Without the cast it gives me red squiggly saying I should cast and when I do I get:
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'playerName'
As I step through, I can watch player and it has the various properties just as it should. Any idea what I'm doing wrong?
The problem is that you are using an anonymous object. I can't really take the credit for that finding though, the answer I found was right here (Go give him an up-vote). Refer to it for complete details.
Essentially, the short of the story is that Anonymous objects are emitted as internal by the compiler. This causes problems when trying to use them as Razor views because they are compiled into a separate assembly by the ASP.Net runtime (internal only allows access in the same assembly).
So, the solution is to define a view model:
public class PlayerViewModel
{
// Replace with the actual type of playerId
public int playerId { get; set; }
// etc...
}
And use it in your controller:
public ActionResult Index()
{
var players = (from p in db.Players
join pb in db.PlayerBackgrounds on p.playerId equals pb.playerID
join t in db.Teams on p.teamAbbre equals t.teamAbbre
select new PlayerViewModel { playerID = p.playerId, ... }).ToList();
return View(players); // Use the strongly-typed model property for your view
// instead of ViewBag.data (It's recommended)
}
And finally in your view:
#* At the beginning of your view *#
#model IEnumerable<PlayerViewModel>
...
#foreach (var player in #Model)
{
<tr class="success ui-dragable playerRow" style="display: none;">
<td>
<input type="checkbox" />
</td>
<td>
#Html.ActionLink(player.playerName, "Details", new { id = player.playerID }, new { #class = "detailsLink" })
</td>
<td>
#player.teamName
</td>
<td>
#player.position
</td>....

Categories