I have view with tasks. Each task has an @Ajax.Action link to add this task to check list. My view:
@foreach (var item in Model.Tasks) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TaskText)
</td>
<td>
@Html.DisplayFor(modelItem => item.TillDate)
</td>
<td>
@Html.EnumDropDownListFor(modelItem => item.State, new { id=item.Id, @class="state"})
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
@Ajax.ActionLink("Add To check list", "AddToCheckList", new { id = item.Id }, new AjaxOptions { UpdateTargetId = "CheckListPartial" });
</td>
</tr>
}
My controller action:
public PartialViewResult AddToCheckList(int id)
{
context.AddTaskToCheckList(id);
return PartialView("_LoadCheckList", context.CheckList);
}
And CheckList class:
public class CheckList
{
public string Name { get; set; }
public List<Task> Tasks { get; set; } = new List<Models.Task>();
}
Now adding works, but I have a problem: I can add one task to check list several times. How can I validate if check list contains task and show error message?
UPD: I've make this with my controller. Validation works, but message is not shown.
public PartialViewResult AddToCheckList(int id)
{
if(context.CheckList.Tasks.Exists(t=>t.Id==id))
ModelState.AddModelError("CheckList", "Check list already contains this task.");
if (ModelState.IsValid)
{
context.AddTaskToCheckList(id);
return PartialView("_LoadCheckList", context.CheckList);
}
return PartialView();
}
Also add this string to my View:
@Html.ValidationMessageFor(model => model.CheckList)
UPD2: My PartialView:
@model TaskTracker.Models.CheckList
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
Текст задания
</th>
<th>
Дата выполнения
</th>
<th></th>
</tr>
@foreach (var task in Model.Tasks)
{
<tr>
<td>
@Html.DisplayFor(modelItem=>task.Value.TaskText)
</td>
<td>
@Html.DisplayFor(modelItem => task.Value.TillDate)
</td>
</tr>
}
</table>