Imagine I have two models: DailyTasks and Task. The initial view is strongly typed with the DailyTasks model, displaying a list of existing tasks for the day. Users can add more tasks to the list/table by clicking the add button. Upon clicking the add button, a partial view linked to the Task model is rendered.
I aim to save any changes made by the user to the existing tasks as well as newly added tasks.
I am currently exploring different methods such as model binding and creating a JSON object of the model to pass it to the controller upon Save. However, I have encountered an issue where only the existing tasks are passed back to the Save controller, and none of the newly added tasks are included.
Model:
public class DailyTasks
{
public int ID { get; set; }
public List<Task> TaskList{ get; set; }
}
public class Task
{
public int Id { get; set; }
public string MyTask { get; set; }
}
Main View:
@model Example.Models.DailyTasks
@using (Ajax.BeginForm("Save", "DailyTasks", new AjaxOptions { HttpMethod = "Post" }))
{
<input type="button" value="Add New Task" id="addBtn" />
<input type="submit" value="Save" id="saveBtn"/>
<table class="table">
<tr>
<th>Column Header Name Goes Here</th>
<th>Column Header Name Goes Here</th>
</tr>
@for (var i = 0; i < Model.TaskList.Count(); i++)
{
<tr>
<td>
@Html.DisplayFor(m => Model.TaskList[i].ID)
@Html.HiddenFor(m => Model.TaskList[i].ID)
</td>
<td>
@Html.DisplayFor(m => Model.TaskList[i].MyTask)
@Html.HiddenFor(m => Model.TaskList[i].MyTask)
</td>
</tr>
}
</table>
}
<script type="text/javascript">
$(document).ready(function () {
$("#addBtn").on("click", function () {
$.get('@Url.Action("AddTask")', function (data) {
$("table tbody").append(data);
});
});
});
</script>
Add New Task ActionResult for Partial View:
public ActionResult AddTask()
{
Task model = new Task();
return PartialView("_AddTask", model);
}
Partial View (_AddTask):
@model Example.Models.Task
<tr>
<td>
@Html.DisplayFor(m => Model.ID)
@Html.HiddenFor(m => Model.ID)
</td>
<td>
@Html.DisplayFor(m => Model.MyTask)
@Html.HiddenFor(m => Model.MyTask)
</td>
</tr>