0

I have some fields which may vary according to type of project. I'm trying to create these fields and take values for them. I tried create labels and TextBoxFor input by iterating inside a foreach loop like this;

<div class="row" id="customerdetailcontent">
@foreach (var detail in customerFields)
{
  <div class="form-group">
      <label class="col-md-3 control-label">@detail</label>
      <div class="col-md-9">
        @Html.TextBoxFor(model => model.CustomerDetail, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CustomerDetail, "", new { @class = "text-danger" })
      </div>
  </div>
}
</div>

When I click Submit and check the parameter arriving to action inside controller, CustomerDetail list is null.

this is the field declaration inside the model

public List<CustomerDetailModel> CustomerDetail { get; set; }

It's been a while since I wrote Razor, I might be making a simple mistake or trying something impossible. What am I doing wrong?

Ege Bayrak
  • 1,139
  • 3
  • 20
  • 49
  • You cannot bind a textbox to a complex property - it binds to a posts back a simple value (e.g. a `string`). And you cannot use a `foreach` loop to generate form controls for a collection. Refer [Post an HTML Table to ADO.NET DataTable](https://stackoverflow.com/questions/30094047/post-an-html-table-to-ado-net-datatable/30094943#30094943). You have not shown your model, but you need something like `@for(int i = 0; i < Mdoel.CustomerDetail.Count; i++) { @Html.TextBoxFor(m => m.CustomerDetail[i].SomeProperty) }` –  Nov 19 '18 at 22:43
  • @StephenMuecke thank you, your comment solved the problem. If you re-send it as an anwer I'd be happy to mark it as accepted answer. – Ege Bayrak Nov 20 '18 at 12:23
  • Your question is lacking information and is a a bit vague and unclear so adding an answer as it stands would not be of help to others –  Nov 22 '18 at 02:19

0 Answers0