0

I'm using ASP.NET MVC 4 and LINQ/SQL. I have an HTML page with a form where I want to render HTML input boxes based on a Model Class. In my view, I'm looping over the model and trying to generate an input box for each table row, but since the model is empty, the input boxes do not show. The model is empty because there is no data in the database yet as that is what I want to collect in my form. When there is data in the model, the values from the database should show in the form.

How can I render the empty input boxes, given that my model is initially empty.

Code is below:

@for (int i = 0; i < Model.Count; i++)
    {  
 <tr>

    <td>                           
      @Html.EditorFor(model => model[i].CustomerName, new { htmlAttributes = new { @class = "form-control" } })
    </td>

 </tr>
 }
user1669296
  • 425
  • 1
  • 6
  • 13
  • 1
    It sounds to me like you want to have a separate input box for adding, outside the loop. – JuanR Oct 19 '17 at 20:20
  • I don't get what you're asking. You want to add a box for each entry in the database, but there's no entry in the database, so you're getting no boxes. Seems like expected behavior. So what's your issue? – mason Oct 19 '17 at 20:24
  • @mason - I'm looking for how to structure the code to account for there being a row in the database and also when there is not a row in the database. I could just an input box outside the loop as the other user mentioned, I was thinking there may be a more elegant way as I'm new to ASP.NET – user1669296 Oct 19 '17 at 20:26
  • 1
    You need an 'Add' button which generates a new row in your table. Refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for a couple of options, and [this one](http://stackoverflow.com/questions/40539321/partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) for a more detailed answer using `BeginCollectionItem` –  Oct 19 '17 at 20:28
  • I think you need to do two things, first is to check if you have an empty model. If you do display input fields that will be used collect details you needjyoy can add a message like 'there is no data yet'. Secondly you will add an action in your controller that will be doing the adding of the collected details into the database. – iAM Oct 19 '17 at 20:45

1 Answers1

1

Use For Loop with a number of box that you need, and validate when the model is null, use a For loop

 @{ 
    if (Model == null)
    { 
      int textboxnumber = 6;//change value on behind code or put a constant number 
      for(int i=0;i<textboxnumber;i++) 
      { 
        <input type="text" placeholder="textbox empty"/> 
      } 
    } 
  }