I have a class setup like this
public class MyCLass
{
//...
public IList<MyInnerClass> InnerClass { get; set;}
}
public class MyInnerClass
{
public string A { get; set;}
public string B { get; set;}
//....
}
in my cshtml form I can put it on all the page and post it back with something like
for(int i=0; i< Model.InnerClass.Count; i++)
{
@Html.EditorFor(m => m.InnerClass[i].A);
@Html.EditorFor(m => m.InnerClass[i].B);
}
But now I need to have a button that can add a new instance of MyInnerCLass‘s inputs below the existing ones dynamically with javascript and still bind everything back properly when I post the page. How would I do this? jQuery is preferred, but I can use anything that works
One way would be to wrap the each row of the for loop in some HTML tag, such as a div or tr, so that it can be referenced with jQuery. Then the you can use one of the generated rows as a template row. Indexes must be replaced with the appropriate value. Suppose you have this HTML output:
You can select the first row with jQuery and then clone it, replace the indexes using regex, then append the row: