0

I am new to MVC. I want to dynamically create textboxes upon user click.

<script>
function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    var colCount = table.rows[0].cells.length;
        for(var i=0; i<colCount; i++) {

            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
            switch(newcell.childNodes[0].type) {
                case "text":
                    newcell.childNodes[0].value = "";
                    break;
                case "checkbox":
                    newcell.childNodes[0].checked = false;
                    break;
                case "select":
                    newcell.childNodes[0].selectedIndex = 0;
                    clear_attrib();
                    break;
        }

    }
    else {
        alert("Cannot add another row.");
    }
}

function deleteRow(tableID) {
    try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                if(rowCount <= 1) {
                    alert("Cannot delete all the rows.");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
    }catch(e) {
        alert(e);
    }
}

and the Razor

<table class="table" id="AddSchedule">
  <tr>
      <td><input type="checkbox" name="chk[]" class="checkbox_style" /></td>
      <td>@Html.EditorFor(model => model.Schedule, new { htmlAttributes = new { @class = "form-control" } })
          @Html.ValidationMessageFor(model => model.Schedule, "", new { @class = "text-danger" })
       </td>
       <td>@Html.EditorFor(model => model.Room, new { htmlAttributes = new { @class = "form-control" } })
           @Html.ValidationMessageFor(model => model.Room, "", new { @class = "text-danger" })
        </td>
        <td>@Html.EditorFor(model => model.Subject, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Subject, "", new { @class = "text-danger" })
         </td>
    </tr>

the adding and removing of textboxes is OK. But I don't know how to save the data in the database. This is my controller

    public ActionResult Create(EmployeeViewModel employeeViewModel) 
{
if (ModelState.IsValid)
    {
      var emp = db.Employee.Create();
      emp.ID = employeeViewModel.ID;
      emp.LastName = employeeViewModel.LastName;
      emp.FirstName = employeeViewModel.FirstName;
      db.Employee.Add(emp);

      var sched = db.FacultySchedule.Create();
      sched.Schedule = employeeViewModel.Schedule;
      sched.Room = employeeViewModel.Room;
      sched.Subject = employeeViewModel.Subject;

      db.FacultySchedule.Add(sched);
      db.SaveChanges();
}

I tried using foreach but it still save only the first value, so i removed it... I think I'm missing something in the mark-up... like adding [] to make it an array just like in PHP. And I don't know how to fix it in the controller.

How can I fix the mark-up and the loop for in the controller for saving? Thanks.

Edit this is the viewmodel

public class EmployeeViewModel
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Schedule { get; set; }
    public string Room { get; set; }
    public string Subject { get; set; }
    public virtual IEnumerable<FacultySchedule> FacultySchedule { get; set; }

}

and these are the domain model

public partial class Employee
{
    public Employee()
    {
        FacultySchedule = new HashSet<FacultySchedule>();
    }
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }

    public virtual ICollection<FacultySchedule> FacultySchedule { get; set; }

}

public partial class FacultySchedule
{
    public FacultySchedule()
    {
        Substitution = new HashSet<Substitution>();
    }
    public int ID { get; set; }
    public int EmployeeID { get; set; }
    public string Schedule { get; set; }
    public string Room { get; set; }
    public string Subject { get; set; }

    public virtual Employee Employee { get; set; }
}
makoto
  • 177
  • 1
  • 4
  • 16
  • You controls are not being named correctly with indexers. [This answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) provide some options for generating the correct html –  Mar 05 '15 at 05:59
  • so does it mean I need to make the 'dynamic add textbox' part in a partial view first because it is not in partial view... thanks – makoto Mar 05 '15 at 06:39
  • I don't know which partial you are referring to. Is this in reference to this link I gave (the option using `BeginCollectionItem`?) –  Mar 05 '15 at 06:43
  • yes, do i need to make it in partial view so that i could implement the Option 1? – makoto Mar 05 '15 at 06:59
  • Yes, you have a partial view for the model, in your case wrapped in `` tags. Then your `addRow` method uses ajax to return the partial and append the html to the table. –  Mar 05 '15 at 07:04
  • Thanks a lot I was able to create indexes on the controls using BeginItemCollection. My next question is how can I save it to the database. I tried to add a `IEnumerable employeeViewModel` as **another** parameter on the Create but it does not work – makoto Mar 05 '15 at 08:22
  • If the partial is `@model EmployeeViewModel` then it should be fine, but you haven't posted the model, or the view or the partial or the controller so impossible to tell. –  Mar 05 '15 at 08:36
  • I edited my post, I added the domain model and the viewmodel that I used in the View and updated the controller – makoto Mar 05 '15 at 09:11
  • If the html being generated is like `` etc then this should post back to `public ActionResult Create(IEnumerable model)` –  Mar 05 '15 at 09:18
  • yes, i already used that, but it causes an error in all the **the model does not contain defenition for 'LastName' ** – makoto Mar 05 '15 at 09:31
  • You haven't even said where there error is occurring. –  Mar 05 '15 at 10:12

0 Answers0