简体   繁体   中英

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" />
}

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM