Loop through numbered properties to generate inputs in Razor Pages - c#

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.

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>
}

How to declare a list that contain an array with 2 types of data?

I have this list so far:
List<object> lista = new List<object>();
foreach (var item in group)
{
lista.Add(new
{
ver = item.FirstOrDefault().vereda.DESCRIPCION,
prod = item.Count()
});
}
ViewBag.veredasEncu = lista;
i have to send that data to a view in order to build a table:
<tbody>
#{
if (ViewBag.veredasEncu != null)
{
List<object> lis = ViewBag.veredasEncu;
for (int i = 0; i < lis.Count(); i++)
{
<tr>
<td></td>
<td></td>
</tr>
}
}
}
</tbody>
I cant get to place the info on the <td> tags cose every item in the foreach iteration throws something this:
item = {ver = "Loma", prod = 5}
how can i make that 2 values look like an array, or is there a way to separate them in order to place them in the correct tag?
I solved the issue by creating a class:
public class dataTab
{
public string ver { get; set; }
public int prod { get; set; }
}
then is just change the loop for this:
lista2.Add(new dataTab
{
ver = item.FirstOrDefault().vereda.DESCRIPCION,
prod = item.Count()
});
so it could be post in the HTML like this:
foreach (var item in ViewBag.veredasEncu)
{
<tr>
<td>#item.ver</td>
<td>#item.prod</td>
</tr>
}
However im not sure that creating a class for every type of list that i need to create is a good idea. IF someone have an idea on how to fill the list in a more generic way please respond this.

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?

Setting static property as Session for getting unique results

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>

C# MVC DropDownListFor in a table of editable records

I am not sure if this is possible, and have not found any similar questions on this.
We have an Edit View that is NOT for a single record, but for the multiple members of a "parent" record. These "child" record need to be edited together (at the same time). ... if possible.
One field in each of these "child" records is a reference to another table, so a select list is required. We use DropDownListFor in all of our standard Edit Views, and the single record edits fine.
Our model for this issue is :
[Display(Name = "Team Member")]
public int Contact_ID { get; set; }
[Display(Name = "Team Member")]
public String Contact_Name { get; set; }
[Display(Name = "Type/Role")]
public int MemberTypeLookUp_ID { get; set; }
[Display(Name = "Type/Role")]
public String MemberTypeValue { get; set; }
[Display(Name = "Type/Role")]
public LookUpList MemberTypeLookUp { get; set; }
We retrieve the first 4 fields via a select from a database table. Straightforward and OK..
Our code to set up the DropDownListFor is :
(edit : new code added within the foreach() loop to manually set the .Selected property of the relevant option within each list to true. This still does not translate over to the actual displayed View...)
foreach (TeamEditViewItem tevi in this.members)
{
tevi.MemberTypeLookUp = new LookUpList("TeamMemberType");
foreach (SelectListItem item in tevi.MemberTypeLookUp.list)
{
if (item.Value == tevi.MemberTypeLookUp_ID.ToString())
{
item.Selected = true;
break;
}
}
}
For completion of this question, the LookUpList code is :
public class LookUpList
{
public SelectList list;
// Return all Active LookUp entries for the passed-in Category.
public LookUpList(String Category)
{
WorkpointContext _db = new WorkpointContext();
int Customer_ID = _db.GetCustomer_ID();
IList<LookUp> items = (from lookup in _db.LookUp
where (lookup.Category == Category)
&& (lookup.IsActive == true)
orderby lookup.DisplayOrder ascending
select lookup).ToList();
this.list = new SelectList(items, "ID", "Value");
}
}
As mentioned, the LookUpList code is fine for a single record on a standard Edit View.
After rendering the page, we get the multiple "child" records listed, however the DropDown List does not hold the existing value for each record. (This is an EDIT not a Create, so values have already been assigned via defaults and other logics - not via DropDown lists on the Create View.
When viewing the source of the page, I can see that each of the DropDown Lists have their own ID.
I have a feeling that our issue is due to the multiple DropDownListFor objects on the page, but cannot figure out WHAT the issue is and WHY we have the issue.
Our View has simple code for the DropDownList :
#Html.DropDownListFor(model => model.members[i].MemberTypeLookUp_ID, Model.members[i].MemberTypeLookUp.list, "--Select--")
#Html.ValidationMessageFor(model => model.members[i].MemberTypeLookUp_ID)
The third parameter has been added because we were always getting the first option in the DropDown Lists and needed to determine if there was a value or not.
We are constantly getting the "--Select--" option displayed in the DropDown Lists, which is a placeholder and not a valid option - therefore the Validation Message is displayed.
(Edit) I have added the complete Edit View cshtml code :
#model WebWorkPoint.Models.TeamEditView
<h3>Edit Team</h3>
#using (Html.BeginForm()) {
<fieldset>
#if (Model.members.Count>0)
{
<table>
<!-- table headings -->
<thead>
<tr>
<td style="text-align:center; border-bottom: 1px solid black; " >
<div class='editor-label'>
#Html.LabelFor(m => m.members.First().Contact_Name)
</div>
</td>
<td class="spacer-border"> </td>
<td style="text-align:center; border-bottom: 1px solid black; " >
<div class='editor-label'>
#Html.LabelFor(m => m.members.First().MemberTypeValue)
</div>
</td>
</tr>
</thead>
<!-- table rows -->
<tbody>
#for (int i = 0; i < Model.members.Count; i++)
{
<tr>
<td style="text-align:center; " >
#Html.HiddenFor(m => m.members[i].Contact_ID)
<div class="editor-field">
#Html.EditorFor(m => m.members[i].Contact_Name)
#Html.ValidationMessageFor(model => model.members[i].Contact_Name)
</div>
</td>
<td class="spacer"></td>
<td style="text-align:center; " >
<div class="editor-field">
#Html.DropDownListFor(model => model.members[i].MemberTypeLookUp_ID, Model.members[i].MemberTypeLookUp.list, "--Select--")
#Html.ValidationMessageFor(model => model.members[i].MemberTypeLookUp_ID)
</div>
</td>
</tr>
}
</table>
}
else
{
<p>There are currently no team members defined.</p>
}
<p>
<input type="submit" value="Update Team" />
#{
sAction = "/" + Model.TableNameValue + "/" + Model.TableNameValue + "Show/" + Model.TableRecord_ID.ToString();
sLinkText = "Cancel";
}
<button type="button" onclick="location.href='#sAction'" >#sLinkText</button>
</p>
</fieldset>
}
(end Edit)
Can anyone shed some light into our issue ? Thank you in advance for any help.
After reading this answer on Stack Overflow , we decided to try the same kind of resolution.
As it turns out, the FULL resolution went as follows :
We still needed to set up the LookUpList in the setup code (but did not need to attempt any select code) :
// other code above ...
foreach (TeamEditViewItem tevi in this.members)
{
tevi.MemberTypeLookUp = new LookUpList("TeamMemberType");
}
The LookUpList() code creates the SelectList as per the original issue/question - no changes required there.
We also needed to replace the DropDownListFor() call on the Edit View :
#Html.DropDownListFor(model => model.members[i].MemberTypeLookUp_ID, new SelectList(Model.members[i].MemberTypeLookUp.list, "Value", "Text", Model.members[i].MemberTypeLookUp_ID), "--Select--")
It seemed repetitive or redundant, but this is what was required. There may be something we could do to clean it further, but it "ain't broke" now, so why try to fix it ?
I must say thank you to #Stephen Muecke and #Mario Lopez for their input, to get us investigating and thinking further afield from what we were doing. Also, thank you to #ataravati for resolving the other issue linked above, to get us to try something else.
Hopefully our issue and resolution might help other coders out there ...
I think what is happening is that all the dropwdowns are being generated with the same Id = MemberTypeLookUp_ID. What I would do is creating a partial view for the child and call it from the main view inside a foreach and pass to this partial view only the child model that has to be populated for and not the whole parent model.

Categories