For loop in model view ASP.NET MVC C# - 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>
}

Related

Model Binding To List Of Objects In ASP.NET MVC with RadioButton

I view list data and I want to edit some field
example as image, list view data, and edit it
i have a field (ex:choosed_value with some value 1,2,3,4,5)
in view, i use radiobutton to get value from choosed_value,
but when i submit to save, i can't get value choosed from radiobutton,
field 'content' saved ok, field 'choosed_value' not save.
my code
in view
view radiobutton
#for (int j = 1; j <= 5; j++)
{
<td>
#Html.RadioButton(Model[i].ID.ToString(), Model[i].choosed_value,Model[i].choosed_value == j) ? true : false )
</td>
}
if choosed_value = 1 then radiobutton with value = 1, checked = true
in controller
[HttpPost]
public ActionResult Index(List<Content> contents)
{
DEMOEntities DbContent = new DEMOEntities();
foreach (Content cont in contents)
{
Content Existed_Cont = DbContent.Contents.Find(cont.ID);
Existed_Cont.Content = cont.Content;
Existed_Cont.choosed_value = cont.choosed_value;
}
DbContent.SaveChanges();
}
please help me ...
I think your radiobutton names are incorrect (first param of Html.RadioButton).
The result input name in browser should not be ID, it should be like [0].choosed_value for correct model binding on POST.
#for (int j = 1; j <= 5; j++)
{
<td>
#Html.RadioButtonFor(x => Model[i].choosed_value, ...)
</td>
}
instead of
#for (int j = 1; j <= 5; j++)
{
<td>
#Html.RadioButton(Model[i].ID.ToString(), Model[i].choosed_value,Model[i].choosed_value == j) ? true : false )
</td>
}
Use the browser dev-tools to see what is actually passed as data to your controller. There should be some fields with the name 'contents' or the model-binder cannot pick them up.
First of all we shouldnt make a database call from action method directly.
Now your ViewModel's list should be of type List<SelectListItem>, in that way you can get the "selected" item's value straight forward.

Binding DropDownListFor In foreach , ASP.NET MVC

Here is my code :
ViewModel
public class FooViewModel{
public Guid BarId { set;get }
}
View :
#model IEnumerable<FooViewModel>
#foreach (var c in Model)
{
<div>
#Html.DropDownListFor(o => c.BarId , (List<SelectListItem>)ViewBag.BarCollection)
</div>
}
the problem is DropDownListFor create the options completely but binding doesn't work.
You cannot use a foreach loop to generate controls for items in a collection. If you inspect the html you will see that you have duplicate name attributes without indexers (and also duplicate id attributes which is invalid html). You need a for loop of a custom EditorTemplate for FooViewModel. Using a for loop (your model must implement IList<T>)
#model IList<FooViewModel>
for (int i = 0; i < Model.Count; i++)
{
#Html.DropDownListFor(m => m[i].BarId, ....)
}
Note the html will now be
<select name="[0].BarId" ..>
<select name="[1].BarId" ..>
etc.

Using MVC4 DropDownList helper for deeply nested properties

In my view I need to create a drop down list for a property that is not in the immediate view model, rather nested within two more levels of view models. It's arranged as so:
patient -> (list)referrals -> (list)bookings.attendanceId
How would I use the DropDownListFor helper in this case? The problem is not finding the List<SelectListItem> but pointing the helper to the scalar value the drop down selection should fill.
First just an opinion, one of the main reason we use view models if to simplify the domain models to only what you explicitly need in the view. So my question to you is why is your view model so complex?
That being said the only way to accomplish what you want to do is to have your drop down list nested inside 2 for loops like this:
#for (var i = 0; i < Model.Referrals.Count; i++)
{
#for (var j = 0; j < Model.Referrals[i].Bookings.Count; j++)
{
#Html.DropDownListFor(m => m.Referrals[i].Bookings[j].AttendanceId, Model.SomeSelectList)
}
}
Try
#for(int i = 0; i < Model.Referrals .Count; i++)
{
for (int j = 0; j < Model.Referrals[i].Bookings.Count; j++)
{
#Html.DropDownListFor(m => m.Referrals[i].Bookings[j].AttendanceId, Model.YourSelectList)

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

VS doesn't recognize a variable

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.

Categories