VSB
VSB

Reputation: 10375

Why Html.Hidden is not working in C# ASP.NET MVC razor view?

I want to populate hidden inputs for a form using foreach in my razor view. It is like this:

@foreach (var commodity in ((FilterViewModel)ViewBag.ViewModel).commodities)
{
    Html.Hidden("commodities", commodity);
}

and here is my ViewModel:

public class FilterViewModel
{
    public string commodityType { get; set; }
    public string department { get; set; }
    public string repository { get; set; }
    public string[] commodities { get; set; }
    public string[] purchaseReportTypes { get; set; }
    public string dateValue_1 { get; set; }
    public string dateValue_2 { get; set; }
}   

Although foreach lopps through items, hidden inputs are not added to my HTML source after rendering. However this one is working just fine and I don't know why Html.Hidden not works:

@foreach (var commodity in ((FilterViewModel)ViewBag.ViewModel).commodities)
{
    <input type="hidden" id="commodities" name="commodities" value="@commodity" />
}

Upvotes: 2

Views: 938

Answers (2)

Peter Smith
Peter Smith

Reputation: 5550

To avoid the multiple identical id values problem try the following (not tested):

@int idCount = 0;
@foreach (var commodity in ((FilterViewModel)ViewBag.ViewModel).commodities)
{
    idCount++;
    @Html.Hidden($"commodities{idCount}", commodity, new { @class="commodities"});
}

Use a jQuery selector with .commodities instead of #commodities.

Upvotes: 0

Cyril Durand
Cyril Durand

Reputation: 16192

You miss a @ before the Html.Hidden

@foreach (var commodity in ((FilterViewModel)ViewBag.ViewModel).commodities)
{
    @Html.Hidden("commodities", commodity);
}

By the way you should consider not having the same id in your html to avoid any problem.

Upvotes: 2

Related Questions