Reputation: 6378
I need to generate labels in view for each item in an array which is in the model.
This is what I have so far.
Reference.cs
public class Reference
{
private string[] itemList = { "Shirt", "T-shirt", "Denim" };
public string[] Item {
get{
return itemList;
}
set {
itemList = value;
}
}
public int ShirtId{get;set;}
public int TShirtId { get; set; }
public int DenimId { get; set; }
}
index.cshtml
@model WebApplication1.Models.Reference
@{
ViewBag.Title = "Index";
}
<h2>Update Your References Here</h2>
<br>
<p> Please type in the reference code of the item in the corresponding text box</p>
<section id="reference-update">
@using (Html.BeginForm()) {
<fieldset>
<legend> Reference Items</legend>
<div class="form-horizontal">
<div class="item">
@Html.LabelFor(model=>model.Item[0])
</div>
<div class="input-lg">
@Html.TextBoxFor(model => model.ShirtId)
</div>
</div>
</fieldset>
}
</section>
But I do not get a label named "Shirt" in the view(A label Named "Item[0]" appears). How do I fix this? Note that I am a beginner.
EDIT: Controller code
public class ReferenceController : Controller
{
// GET: Reference
[Authorize]
public ActionResult Index()
{
return View("Index");
}
}
Upvotes: 0
Views: 3990
Reputation: 5137
I would have structured your model differently that would simplify this scenario:
public class ItemModel
{
public int ItemId { get; set; }
public string Description { get; set; }
public string Label { get; set; }
}
public class ItemListViewModel
{
public IList<ItemModel> ItemList { get; set; }
}
Now your view can operate on an object of type ItemListViewModel
and iterate through items stored in it.
Advantage over your current approach:
Upvotes: 1
Reputation: 4998
It won't work for @Html.LabelFor()
since as you look at helper's signature:
public static MvcHtmlString LabelFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression
)
you need an expression which identifies property to display. Array item is not a property which can be displayed.
You can change your HTML to:
@model WebApplication1.Models.Reference
@{
ViewBag.Title = "Index";
}
<h2>Update Your References Here</h2>
<br>
<p> Please type in the reference code of the item in the corresponding text box</p>
<section id="reference-update">
@using (Html.BeginForm()) {
<fieldset>
<legend> Reference Items</legend>
<div class="form-horizontal">
@foreach(var item in Model.Item)
{
<div class="item">
<label>@item</label>
</div>
}
<div class="input-lg">
@Html.TextBoxFor(model => model.ShirtId)
</div>
</div>
</fieldset>
}
If you want just to generate label for each item in your model.
EDIT:
Change your controller code to:
public class ReferenceController : Controller
{
// GET: Reference
[Authorize]
public ActionResult Index()
{
var model = new WebApplication1.Models.Reference();
return View("Index", model);
}
}
Upvotes: 2
Reputation: 3061
use @Html.Label(Model.Item[0])
<div class="item">
@Html.Label(Model.Item[0])
</div>
Upvotes: 0