I'm building a page where I need to add document templates. Each document will have unknown number of sections. The user will be able to give a name to the template and add as many sections as he wants. The section will have name and content. I have followed the example here: Create dynamic forms that grow at run time However the collections with section is always empty. Here are my models, controller and some code from the view.
NewDocumentViewModel.cs
public class NewDocumentViewModel
{
public string Name { get; set; }
public List<SectionViewModel> Sections { get; set; }
public NewDocumentViewModel()
{
this.Sections = new List<SectionViewModel>();
}
}
Here is the SectionViewMode.cs
public class SectionViewModel
{
public int Id { get; set; }
public string SectionName { get; set; }
public string SectionContent { get; set; }
public int Position { get; set; }
}
Following the example from the link above I have created a View file called Section.cshtml with the follow content:
@model SectionViewModel
<input type="text" asp-for="SectionName" class="sections" />
<input type="text" asp-for="SectionContent" class="contents" />
Then in my View called SaveTemplate I have the following in the form:
<form asp-controller="Templates" asp-action="SaveTemplate">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<p>
<a id="addSection" class="btn btn-success">Add new section</a>
@Html.EditorFor(f => f.Sections)
</p>
<div class="form-group" id="sectionContainer">
</div>
<button type="submit" class="btn btn-primary">Add document</button>
</form>
And here is the JavaScript that is adding a new section:
<script>
var count = 1;
$('body').on('click', '#addSection', function () {
var i = $(".sections").length;
var y = $(".contents").length;
var structure = $('<div>' +
'Section name:<br />' +
'<input type = "text" name="Section[' + i + '].SectionName" class = "form-control sections" /><br />' +
'Section content:<br />' +
'<textarea name="Section[' + y + '].SectionContent" id = "editor' + count + '" class= "form-control contents" placeholder = "Description" ></textarea >' +
'</div > ');
$('#sectionContainer').append(structure);
CKEDITOR.replace('editor' + count);
count++;
});
</script>
I don't have much code in the controller as I have just created added to see if I'll get all the data from
the View when debugging:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveTemplate(NewDocumentViewModel model)
{
try
{
// TODO: Add insert logic here
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
What is the reason for the Section collection to be always empty and how to solve this?
` fixed the issue. – Ivan Oct 26 '20 at 18:52