Only print an item once from Model in the View - c#

I have a Model that produces an IENumerable, so I already have a foreach loop to iterate and organize each of my model's contents. However, I have one piece of the model that I only want to print once. Here is what I have now:
#foreach (var item in Model)
{
if (item.Site == "Source Search")
{
More Results
}
}
The problem is that this causes it to print the link 50 times (how many items I have in each Model), but I only want it once.
Any ideas?

Use a flag.
bool found = false;
#foreach (var item in Model)
{
if (item.Site == "Source Search" && !found)
{
found = true;
More Results
}
}

The simplest way would be to simply add a break to exit the loop after it's first rendered:
#foreach (var item in Model)
{
if (item.Site == "Source Search")
{
More Results
break;
}
}

Related

Filter a list in the view

I have a simple #foreach loop in a view that iterates over a list:
#foreach (var record in Model.ChangeOrder.Change_Order_Dash_List)
{
....
}
Works great! But, depending on a boolean in the model, I may need to filter this list. This, I am having trouble figuring out. This is what I'm trying:
#{List<MCA.Models.ChangesVM.ChangeOrderInfo> Change_Order_Dash_List = new List<MCA.Models.ChangesVM.ChangeOrderInfo>();}
#if (Model.ViewChangeOrdersFromChart)
{
Change_Order_Dash_List = Model.ChangeOrder.Change_Order_Dash_List.Where(l => l.Implement_Date == Model.ViewChangeOrdersOnDate).ToList<MCA.Models.ChangesVM.ChangeOrderInfo>();
}
else
{
Change_Order_Dash_List = Model.ChangeOrder.Change_Order_Dash_List;
}
#foreach (var record in Change_Order_Dash_List )
{
....
}
But the results are weird. When I render the page, the list looks to be empty. No data is rendered to the screen. And if I set a breakpoint anywhere on the page, it is never hit.
What am I doing wrong?
Thanks!
Another (and IMO more simple) syntax to achieve this, is to merge the if condition into the Where using the || operator like this:
yourList.Where(l => !Model.ViewChangeOrdersFromChart ||
l.Implement_Date == Model.ViewChangeOrdersOnDate)
This will filter the list only when Model.ViewChangeOrdersFromChart is true.
This way you don't need the if condition at all.
Well, for whatever weird reason, this did not work:
#if (Model.ViewChangeOrdersFromChart)
but this did...
#if (Model.ViewChangeOrdersFromChart == true)

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
}

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);

Remove multiple items from observablecollection in silverlight

how can i remove multiple items from observablecollection in silverlight.in my project i have one datagrid populating more than one items.in every row contain one checkbox also.if i select more than one row by selecting checkbox and click delete button ,i want to delete all the item from the collection.
public void delete(object parameter)
{
foreach (var x in Book)
{
if (x.Ischeck == true)
{
Book.Remove(x);
}
}
}
it cause error.can't change observablecollection
You can use below mentioned code snippet instead:
foreach (var x in Book.ToList())
{
if (x.Ischeck)
{
Book.Remove(x);
}
}
OR
for (int i = Book.Count - 1; i >= 0; i--)
{
if (Book[i].Ischeck)
{
Book.RemoveAt(i);
}
}
I assume that the error message is a bit different. To be more precise, it is:
Collection was modified; enumeration operation may not execute.
To work around this problem, one possible solution is this:
foreach (var itemToRemove in Book.Where(x => x.Ischeck).ToList())
{
Book.Remove(itemToRemove);
}
This will get all items you want to remove and put them into a new list. When you now remove items from Book you are not disturbing the list you are currently iterating over as this is an independent instance.
Using Where before calling ToList reduces the number of references you copy to the new list to only those that really need to be copied.
Simply get a list of the objects contained first:
public void delete(object parameter)
{
foreach (var x in Book.ToList())
{
if (x.Ischeck == true)
{
Book.Remove(x);
}
}
}
The reason for this is that you can't remove elements from an observable collection while you're enumerating the elements. By calling ToList() you enumerate the whole collection first, store it in a list and then check what to remove.

Categories

Resources