How to control outputting data in #foreach - c#

How can I control the number of outputting data in #foreach section?
For ex, in #foreach(var x in Model){} I want to get only first 10 data in that model, what am I supposed to do?

Assuming your Model is a collection type(Ex :IEnumerable<T>), You can use LINQ Take method.
#model IEnumerable<SomeViewModel>
#{ var tenItems = Model.Take(10);} // Get the 10 items from the collection
#foreach (var x in tenItems)
{
<p>#x.Name</p>
}
Also, If you want you can order by the results before taking the 10 items,
#{ var tenItems = Model.OrderBy(s=>s.SomePropertyOfYourClass).Take(10);}

Related

c# Retrieving value in controller from dynamically created check boxes in view

I have the following code in my view:
#foreach (var x in model)
{
<input type="checkbox" name="#x.name" /> #x.name
}
That loop will create about 10 check boxes with each of them having a unique name generated during the runtime. The whole point of this is to make this dynamic without me having to type the values of each name. So when I am trying to check in my controller if each of these check boxes are checked or not, how do I do it? Normally, I would pass a parameter to my controller
public ActionResult MyController(string/bool checkboxName)
and this would work fine if I had one checkbox. However, passing 10 parameters for each check box in the controller sounds insane! What if I add more to x in model later so that I have 20 check boxes?
In the loop you are creating the checkboxes, add them to an ICollection and then iterate over that collection looking for CheckBox.Checked.
I'm certain there is a helper function for that in MVC but I'm traveling and don't quite remember it. Something like this should work, adapt as needed.
Note: This assumes they are all on the same page.
#foreach (var control in this.Controls)
{
if (control is CheckBox)
{
if (((CheckBox)control).Checked)
{
//record as you need
}
}
}
I think one of the ways to do this, which might not be ideal but can still work is to use the FormCollection in the MVC framework since you are using a loop, you can loop the elements in your action
/// your view side
#foreach (var x in model)
{
<input type="checkbox" name="#x.name" /> #x.name
}
///The action side
public ActionResult MyController(FormCollection collection, YourModel model)
{
foreach (var x in model)
{
bool IsThisCheked= Convert.ToBoolean(collection[x.name].ToString());
}
}
I think you can pass the whole list of checkboxes to the post controller and then iterate through them like
[HttpPost]
public ActionResult About(List<Requirements> requirements)
{
foreach (var item in requirements)
{
if (item.IsSelected == true)
{
//perform some operation
}
}
List is the list that I passed from view to controller on submitting the form
Now coming to view it can be something like this
#for (int i = 0; i < Model.Requirements.Count; i++)
{
#Html.HiddenFor(m => m.Requirements[i].RId)
#Html.CheckBoxFor(m => m.Requirements[i].IsSelected, new { id = "requirements_" + i, #class = "divider" })
#Html.DisplayFor(m => m.Requirements[i].RName)
}
RId,RName,IsSelected(someproperty to store boolean) are my model properties related to checkboxlist

Unable to use Viewbag List Items in Razor foreach loop

I have an Images table linked to an Item table (one Item can have many Images). They are linked by the Item Id.
I want to return all images for an Item on the details page. I have been trying to use a Viewbag to achieve this (below).
Controller:
ViewBag.imageFile = (from f in storeDB.Images
where f.ItemId == id
select f.ImageURL).ToList();
View:
#foreach (var image in ((List<string>)ViewBag.imageFile))
{
#ViewBag.imageFile
}
The above will return 'System.Collections.Generic.List`1[System.String]' for each ImageUrl.
I believe the issue is that an object is being return rather than the actual List item string value but cannot figure out how to convert it to the string I need. The plan is to edit this foreach to create an img link for each URL.
I also have the following Viewbag (testing to see I was able to get the Urls at least):
ViewBag.imageURL = string.Join(",", ViewBag.imageFile);
The above returns the correct URLs but they are all in one string separated by a comma.
Appreciate any help.
Inside the loop in the view, you should use the loop variable:
#foreach (var image in ((List<string>)ViewBag.imageFile))
{
#image
}
ViewBag.imageFile is the complete list and will always be, even inside the loop. The image loop variable will be the current item from the list on every turn of the loop.
ViewBag does not require a type casting:
#foreach (var image in ViewBag.imageFile))
{
#image
}

How to display list returned to strongly typed partial view

I have a form with a lookup. I want to display the results of the lookup in the form so the user can select a result and then it would populate a field on the form (to be submitted with the form). I have a partial view in the form with the search box. That passes a string (pacupc) to the controller. However, I don't know how to display the list that's being return to the partial view.
In my controller:
PriceAssociationLookup pacRep = new PriceAssociationLookup();
return PartialView("_PacSearchResultsPartial", pacRep.GetPacs(pacupc));
definition for GetPacs in class:
IEnumerable<IPriceAssociationLookupRepository> IPriceAssociationLookupRepository.GetPacs(string upc)
{
using (PortalDataEntities entities = new PortalDataEntities())
{
var priceAssociationLookups = (from priceassociationlookup in entities.PriceAssociationLookups
where priceassociationlookup.Upc == upc
select priceassociationlookup).ToList();
return priceAssociationLookups;
}
}
and the partial view the lookup results are being sent to:
#model List<Portal.BusinessModel.Entities.PriceAssociationLookup>
#{
//How to display the list of results?
}
You simply loop them like this:
#model List<Portal.BusinessModel.Entities.PriceAssociationLookup>
#foreach(var price in Model)
{
#price.Upc
}
You can output any of your properties by using the #price.Property notation.
Please note if you are posting the items back you need to use a for loop and index them.

For specific number of times

I am trying to do something like this in my HTML:
#foreach (var item in Model) {
However rather than do it for every entry I only want the first 6 items in the model. Does anyone know the syntax? Have tried a few with no sucess.
How about using Take LINQ method
#foreach (var item in Model.Take(6))
don't forget to add namespace System.Linq in your view
You could use a simple for loop.
e.g. for(int i = 0; i < 6; i++)
You can use Enumerable.Take<TSource> Method: Returns a specified number of contiguous elements from the start of a sequence.
Eg.
#foreach (var item in Model.Take(5)) {
Refer:
Enumerable.Take Method

Set order of items in the FOREACH

My controller passes a list of objects to my view allowing me to:
#foreach (var optiongroup in Model)
{
Within the Model is an IEnumerable<Option>. I need to sort this list of options such that when I:
#foreach (var option in optiongroup.Options){
I end up with a list where items are sorted on the property called option.SortOrder instead of the ordinal position of each item.
So how do I get a list sorted prior to the foreach? I've tried:
#foreach (var option in optiongroup.Options.OrderByDescending(o => optiongroup.SortOrder))
and:
IEnumerable<Option> allOptions = optiongroup.Options.OrderByDescending(o => optiongroup.SortOrder);
// then foreaching the allOptions list
but have yet to achieve joy.
thx
This
IEnumerable<Option> allOptions = optiongroup.Options.OrderByDescending(o => optiongroup.SortOrder);
should be
IEnumerable<Option> allOptions = optiongroup.Options.OrderByDescending(o => o.SortOrder);

Categories

Resources