VS doesn't recognize a variable - c#

I have this code in my view
#model IEnumerable<P.Models.A>
#{
ViewBag.Title = "Images";
}
<h2>Images</h2>
#int i = 0;
<table>
#foreach (var item in Model)
{
if(i % 3 == 0){
}
}
</table>
VS says to me that i doesnot exist in the current context
what am i doing wrong please?
I tried to add # before i but still got the same error.

Try defining your variable like this:
#{int i = 0;}
Also inside the body of the foreach loop you probably want to be modifying/incrementing the value of this variable.
Oh and you might consider using a for loop instead:
<h2>Images</h2>
<table>
#for (var i = 0; i < Model.Count; i++)
{
if (i % 3 == 0)
{
}
}
</table>
But of course the best would be to define a view model instead of writing such loops inside your view.

Related

For loop in model view ASP.NET MVC C#

Can I use a for loop to show the model view list? Or do I have to use foreach?
If yes, can anyone show me an example please? Thank you.
#model IList<TestMVC1.Models.Account>
#{
ViewBag.Title = "Index";
}
<h2>Accounts List</h2>
#{var student = ViewBag.AccoutList; }
#for (int i = 0; i < student.Count; i++)
{
<div>#student[i].CounterID</div>
<div>#student[i].AccountID</div>
<div>#student[i].AccountName</div>
}
#foreach (var item in Model)
{
<div>#item.CounterID</div>
<div>#item.AccountID</div>
<div>#item.AccountName</div>
}
I want to use it with for loop not foreach but it's not working! I mean the model not the viewBag
#for (int i = 0; i < Model.Count ; i++)
{
<div>#model[i].CounterID</div>
<div>#model[i].AccountID</div>
<div>#model[i].AccountName</div>
}
You must use the #model to define the type of model in top of view file.
But if you want to access the data you should use Model or #Model.
Change the #model to #Model
#for (int i = 0; i < Model.Count ; i++)
{
<div>#Model[i].CounterID</div>
<div>#Model[i].AccountID</div>
<div>#Model[i].AccountName</div>
}

How to access each item in a list of dictionaries in c# without using foreach?

I have a list of dictionary like this
public List<Dictionary<string, object>> Data { get; set; }
From within the a razor view, I want to loop over the list and for each item in the list I want to display it's directory content.
Here is a screenshot of my object
Here is what I have done inside my view
#for (int y = 0; y < Model.Data.Count; y++)
{
<tr>
#for (int x = 0; x < Model.Data[y].Count; x++)
{
<td>#Model.Data[y][x].Value</td>
}
</tr>
}
But this is giving me an error
Compiler Error Message: CS1502: The best overloaded method match for
'System.Collections.Generic.Dictionary.this[string]'
has some invalid arguments
What am I doing wrong here? How can I loop through the data correctly?
Note: I don't want to use foreach loop here because I need to be able to know the previous row/next row and I also want to sum some records in the view
Your dictionary's key is string type, but in your code you are passing an integer value as the key (value of variable x) when trying to access the value.
You may iterate through the dictionary keys and use that to get each item value.
This should do it.
#foreach(var key in Model.Data[y].Keys)
{
<td>#Model.Data[y][key].Value</td>
}
Or even a fullblown foreach solution
#model SomeClassWhichHasTheDataPropertyWhichIsTheDictionary
#foreach(var dict in Model.Data)
{
<tr>
#foreach(var key in dict.Keys)
{
<td>#dict[key]</td>
}
</tr>
}
The dictionary's keys are strings, not integers. But if you don't want to use a foreach on the dictionary, you can copy the key-value pairs into a list, and walk through that in a conventional for loop:
#for (int y = 0; y < Model.Data.Count; y++)
{
<tr>
var kvpairs = Model.Data[y].ToList();
#for (int x = 0; x < kvpairs.Count; x++)
{
var o = kvpairs[x].Value;
<td>#o</td>
}
</tr>
}
You could try something like the following:
#foreach(var item in Model.Data)
{
<tr>
foreach(var key in item.Keys)
{
<td>item[key]</td>
}
</tr>
}
Why you get this error message?
The reason is that the keys of your dictionaries are strings, not integers.
Dictionary<string, object>

error when used foreach loop in mvc 5

I want to create 2 list ul from database. Following my code:
<ul>
#foreach (var item in subCate)
{
if (i == 6)
{
</ul><ul>
}
<li>#item.Name</li>
}
</ul>
but i don't know has error at
if (i > 6)
when i use
</ul><ul>
but when i replace
<li>#item.Name</li>
then not error.
How can i fix? Thanks all.
You have not declared an i variable, change it to a for loop instead:
<ul>
#for(var i = 0; i < subCate.Count; i++)
{
if (i == 6)
{
#:</ul><ul>
}
<li>#subCate[i].Name</li>
}
</ul>
You can also output the un-balanced tags with the #:
You can continue using your foreach, make sure to check the index of the current item in your collection:
<ul>
#foreach (var item in subCate)
{
if (subCate.IndexOf(item) == 6)
{
#:</ul><ul>
}
<li>#item.Name</li>
}
</ul>

Using Razor to return strings in array

I am taking an string[] from my Model and it has about 25ish strings in it at any given time.
#model PostProcessPartSelectionViewModel
#{
var i = 0;
foreach (var part in Model.PartsAllowedAsSeed)
{
<input type="checkbox" id="[#i]" name="PartsAllowedAsSeed" value="#part" />
<span>#part</span>
<br />
i++;
}
}
I set up a #foreach loop in Razor to display a checkbox and label for each string, but when I debug, #part renders to System.Object[]. There are 25 checkboxes with 25 "System.Object[]" labels.
Eventually, I'm going to want to return any checked strings back to the model, but right now I just want to know how I can get Razor to render the actual string value.
Don't use foreach in razor, use a for loop so you can directly bind to your model:
#for (int i = 0; i < #Model.PartsAllowedAsSeed.Length; i++)
{
<input type="checkbox" id="[#i]" name="PartsAllowedAsSeed" />
<span> #Model.PartsAllowedAsSeed[i] </span>
<br />
}
as for your System.Object[], you can do string.Join(", ", #Model.PartsAllowedAsSeed[i]) or some equivalent to meet your needs
My case was pretty specific, so I don't think this will apply to anyone. I had a Object[] with objects in it and I wanted to display each child object as a string with Razor. I used a hack to cast the Object[] to a list, then append brackets to each list entry and reported each string back to Razor. For now, I don't need to bind directly to the model, so I opted to just use a foreach.
Razor Code:
#{
var i = 0;
#foreach (var item in Model.PartsAllowedAsSeed)
{
<input type="checkbox" id="#i" name="PartsAllowedAsSeed" />
<span>#Html.ConvertToArray(item)</span>
<br />
i++;
}
}
Helper Class:
public static MvcHtmlString ConvertToArray(this HtmlHelper htmlHelper, object source)
{
var src = source as IEnumerable;
if (src == null) return MvcHtmlString.Create(string.Empty);
var sourceAsList = src.Cast<Object>().ToList();
var output = new StringBuilder();
output.Append("[");
for (var index = 0; index < sourceAsList.Count; index++)
{
var item = sourceAsList[index];
output.Append(item);
if (index != (sourceAsList.Count - 1)) output.Append(", ");
}
output.Append("]");
return MvcHtmlString.Create(output.ToString());
}

Razor not so smart detecting C# from html

I need to print this html in a view:
#foreach (string indices in Model.Indices)
{
if (counter == 1)
{
Response.Write("<tr>");
}
Response.Write("<td><span class='select'>#Html.CheckBox('nome',false)</span>)"); #indices Response.Write("</td>");
if (counter > 4)
{
Response.Write("</tr>");
}
}
This will print the html markup which I want to create.
I know I could only write the html but Razor is complaining that I am not closing the foreach.
This was my first try:
#foreach (string indices in Model.Indices)
{
if (counter == 1)
{
<tr>
}
<td><span class='select'>#Html.CheckBox('nome',false)</span> #indices </td>
#if (counter > 4)
{
</tr>
}
}
Razor requires that HTML tags be well-formed; otherwise, it wouldn't know when to go back to code context.
You can bypass this restriction by prefixing the line with #:.
However, the correct way to do this is to group your collection into a collection of groups of 4 items, and use a nested foreach.
If i right understand what do you want (Do you want to display first four elements from Model.Indices?), you should move your and tags out from your foreach. Something like this:
<tr>
#{var counter = 1;}
#foreach (string indice in indices)
{
if(counter>4)
{break;}
<td><span class='select'>#Html.CheckBox("nome", false)</span> #indice </td>
counter++;
}
</tr>

Categories