Tools & Pltaform: ASP.NET Core MVC 3.1, Visual Studio 2019, Win 10
Update: It's an Upsert view. I'm trying to loop through properties of the model in Razor page to generate labels and input HTML elements inside the form tag, but the rendered HTML has the "Item" (the name of the variable in foreach) as the value for id, name and *for HTML attributes.
Rendered HTML in browser
<div class="form-group row">
<div class="col-3">
<label for="item">item</label>
</div>
<div class="col-6">
<input class="form-control" type="text" id="item" name="item" value="Author">
<span class="text-danger field-validation-valid" data-valmsg-for="item" data-valmsg-replace="true"></span>
</div>
</div>
HTML displayed in the browser
Razor foreach loop producing the HTML
@{ var propList = new string[] { "Name", "Author", "ISBN" };}
@foreach (var item in propList)
{
<div class="form-group row">
<div class="col-3">
<label asp-for="@item"></label>
</div>
<div class="col-6">
<input asp-for="@item" class="form-control" />
<span asp-validation-for="@item" class="text-danger"></span>
</div>
</div>
}
Can someone explain why this is happening?
Update:
Based on '@Ben Sampica' suggestions, I have made these changes,
How would my view look like, I mean I remember using Model List for a table like view (I have used ASP.NET MVC a few years back, now jumping to .net core), here are the changes I have made,
View:
@foreach (var book in Model.Books)
{
<div class="form-group row">
<div class="col-3">
<label asp-for="@book.Name"></label>
</div>
<div class="col-6">
<input asp-for="@book.Name" class="form-control" />
<span asp-validation-for="@book.Name" class="text-danger"></span>
</div>
</div>
}
I'm using the exact View model as you described "BooksViewModel"
I haven't stated that in the question before but to be clear I'm creating an Upsert view, so now the ViewModel is a list although I'm only concerned with a single record at a time, the view model is empty on create action because there is no data in the list.