0

I want to create table can be edited by pressing "Delete" buttons in each row to remove dictionary item in the row and "Insert" to add new row that contains new dictionary item and append it to existing dictionary key and value.

Model combines two models

    namespace myproject.Models
    {
        public class ProjectAndStudentModels
        {
            public Project project { get; set; }
            public Dictionary<int,string> StudentsAndID { get; set; }
        }
    }

View

        @model myproject.Models.ProjectAndStudentModels
        @using (Html.BeginForm("Edit", "Home", FormMethod.Post))

        <table id="myTable">
           <td><input type="button" value="insert" /></td>
     @for (var i = 0; i < Model.StudentsAndID.Count; i++)
                {
                    var item = StudentsAndID.Count.ElementAt(i);
            <tr>
           <td><input type="button" value="Delete" />
           </td>
            <td> 
            <input type="text" name="example[@i].Value" value="@item.Value" class="input-sm dictionary" />
            </td>
            <td> 
            <input type="text" name="example[@i].Key" value="@item.Key" class="input-sm dictionary" />
           <input type="button" value="-" class="btn btn-danger removeStudent" onclick="removeStu(@i)">

        </tr>
        }
 <tr><td>
 @Html.LabelFor(model => model.project.Year, "Year", new { @style = "display:inline-block" })
 @Html.EditorFor(model => model.project.Year, new { htmlAttributes = new { @Name = "Year", @class = "input-sm" } })
 @Html.ValidationMessageFor(model => model.project.Year)
 </td></tr>
<tr><td> <input type="submit" value="submit"></td> </tr>
</table>
   }

jquery code something like this

    function removeStu(j) {
        $("[name='example[" + j + "].Key']").remove();
        $("[name='example[" + j + "].Value']").remove();       
    }
 function add (){

}

How to add new added input items to dictionary with keep increasing @i index ? for example if dictionary count is 5 new added items must be example[6]

I did it in jquery by passing the index of dictionary ( @j ) but how to add it to dictionary in the model not only in html

Rawan
  • 13
  • 4
  • 1
    1. Do not use a `Dictionary` in a view - use a `List` so you can strongly bind to your model. 2. Refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for some options –  Apr 04 '18 at 06:43
  • @Stephen I used Dictionary to map each key with value and I passed it to view as model – Rawan Apr 04 '18 at 06:45
  • If you want to ignore good advice No no I just ask – Rawan Apr 04 '18 at 06:48
  • Checked out this [so thread](https://stackoverflow.com/questions/5191303/asp-net-mvc-binding-to-a-dictionary)? – dsdel Apr 04 '18 at 07:58

0 Answers0