2

I have a client that asked me to do a web application that works like this(I can´t add image because I´m new at Stack Overflow and it requires reputation of 10 to do it).

When the page loads, it reads a database table and adds 'email' textboxes for each record.

By clicking in 'NEW' it adds a new textbox.

Upon clicking on Save, if a textbox is modified, it updates the record. And If a new textbox was added, it insert into the table.

I have already done that in Classic Asp with a mix of vb/asp, html with hidden inputs, javascript and SQL database procedures. But for each new form that requires this functionality I found it a too cumbersome work and not very productive.

I´m a bit new to .Net WebForms and completely new to MVC. I wonder if is there a easier way to do this with this technologies?

Thank you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Art
  • 237
  • 4
  • 19
  • To render existing objects in a collection, your need to use a `for` loop or a custom `EditorTemplate. To dynamically add new items to a collection you need javascript/jquery. [This answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) gives 2 options as to how you can do that. –  Feb 11 '15 at 11:24
  • Thanks @StephenMuecke, The second option is more or less what I´m already doing with classic asp. Does not work very well for me because I have to create several different forms and with several fields. The option 1 I´m yet trying to understand due to my lack of knowledge of .Net stuff. – Art Feb 11 '15 at 11:33
  • For dynamic manipulation of UI, it is better to go for some two-way binding JS framework. I prefer 'knockout.js' for its simplicity. – Thangadurai Feb 12 '15 at 06:37

1 Answers1

1

First of all, in MVC you will need a so called display model for the items that you want to display in the view. Let's say that the e-mail addresses belong to a User object and that they are of type 'String'. In that case, the model can be a List of User objects.

Your view can then use this model like this:

@model List<User>

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table>
            @for (int i = 0; i < Model.Count;i++ )
            { 
                <tr>
                    <td>@Html.TextBox("users[" + @i + "].Email", Model[i].Email)</td>
                </tr>
            }

        </table>
    }

An excellent article about binding to a list of objects can be found here: http://www.binaryintellect.net/articles/b1e0b153-47f4-4b29-8583-958aa22d9284.aspx

Good luck!

Robert
  • 1,049
  • 1
  • 10
  • 15