У меня есть форма в cshtml, которая вводится в модель, но продолжает пропускать некоторые значения, добавленные внутри блока кода for, в частности значения GroupPerDay.
<form method = "post" asp-action = "Create" class = "row g-3">
<div class = "row g-3 align-items-center">
<div class = "row-cols-auto">
<input type = "text" hidden class = "form-control-plaintext" value = "@Model.Department.DepartmentId" asp-for = "Department.DepartmentId" />
</div>
</div>
<div class = "row g-3 align-items-center">
<div class = "col-auto">
<label for = "SubDate" class = "col-form-label">NGÀY ĐĂNG KÝ: </label>
</div>
<div class = "col-auto">
<input type = "date" id = "SubDate" asp-for = "DayGroup.SubcriptionDate" class = "form-control" />
<span asp-validation-for = "DayGroup.SubcriptionDate" class = "text-dark"></span>
</div>
</div>
<div class = "mb-3 row">
<div class = "col-sm-3">
<input type = "text" readonly class = "form-control-plaintext" value = "DS HỌ TÊN" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 1" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 2" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 3" />
</div>
</div>
@for (int i = 0; i < Model.Department.Persons.Count; i++)
{
int j = Model.Department.Persons[i].GroupPerDay.Count - 1;
<div class = "col-auto">
<input type = "text" hidden readonly asp-for = "Department.Persons[i].PersonId" value = "@Model.Department.Persons[i].PersonId" />
<input type = "text" hidden readonly asp-for = "Department.Persons[i].Name" value = "@Model.Department.Persons[i].Name" />
<input type = "text" hidden readonly asp-for = "Department.Persons[i].GroupPerDay[j].Id" value = "@Model.Department.Persons[i].GroupPerDay[j].Id" />
</div>
<div class = "row">
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext" asp-for = "Department.Persons[i].GroupPerDay[j].Person.Name" value = "@Model.Department.Persons[i].GroupPerDay[j].Person.Name" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[j].Set1" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[j].Set2" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[j].Set3" />
</div>
</div>
}
<div class = "row g-3 align-items-center">
<div class = "col-auto">
<button class = "btn btn-primary" type = "submit">Submit</button>
</div>
<div class = "col-auto">
<a class = "btn btn-danger" asp-controller = "Home" asp-action = "Index">Cancel</a>
</div>
</div>
</form>
Модели
public class CreateGroupViewModel
{
public string AppUserId { get; set; }
public AppUser AppUser { get; set; }
public Department Department { get; set; }
public DayGroup DayGroup { get; set; }
}
public class DayGroup
{
public string Id { get; set; }
public DateTime SubcriptionDate { get; set; }
public Group Group { get; set; }
public List<PersonInGroupPerDay> PersonInGroups { get; set; }
}
public class PersonInGroupPerDay
{
public string Id { get; set; }
public DayGroup DayGroup { get; set; }
public Person Person { get; set; }
[DefaultValue(0)]
public int Set1 { get; set; }
[DefaultValue(0)]
public int Set2 { get; set; }
[DefaultValue(0)]
public int Set3 { get; set; }
}
Ввод для формы
Модель действия Post после ввода
Я хочу, чтобы он добавил значение, которое я вводил в список.
Я попробовал <input class = "btn btn-primary" type = "Submit" />
и даже javascript с функцией Onclick, но он не работает
Если вам нужна дополнительная информация, я могу добавить то, что необходимо, в комментарий.
Полезная нагрузка для метода POST заполнена правильными значениями в правильных индексах, поэтому нет проблем с тем, что mvc составляет модель представления и не имеет значений.
Как вы определяете свою модель? I want it to add the value I input into the List
Хотите сложить 9 чисел в трех столбцах CA1, CA2 и CA3?
Сумма входных данных будет зависеть от количества людей в отделах. Три столбца предназначены для трех разных подходов в день: думайте об этом как о завтраке, обеде и ужине. Я хочу, чтобы значение было связано с отдельным человеком в отделе.
Вы просто добавляете поля ввода для последнего Persons[i].GroupPerDay
элемента.
int j = Model.Department.Persons[i].GroupPerDay.Count - 1;
Нам также нужно добавить скрытые поля для остальных Persons[i].GroupPerDay
элементов.
Попробуйте этот код:
<form method = "post" asp-action = "Create" class = "row g-3">
<div class = "row g-3 align-items-center">
<div class = "row-cols-auto">
<input type = "text" hidden class = "form-control-plaintext" value = "@Model.Department.DepartmentId" asp-for = "Department.DepartmentId" />
</div>
</div>
<div class = "row g-3 align-items-center">
<div class = "col-auto">
<label for = "SubDate" class = "col-form-label">NGÀY ĐĂNG KÝ: </label>
</div>
<div class = "col-auto">
<input type = "date" id = "SubDate" asp-for = "DayGroup.SubcriptionDate" class = "form-control" />
<span asp-validation-for = "DayGroup.SubcriptionDate" class = "text-dark"></span>
</div>
</div>
<div class = "mb-3 row">
<div class = "col-sm-3">
<input type = "text" readonly class = "form-control-plaintext" value = "DS HỌ TÊN" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 1" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 2" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 3" />
</div>
</div>
@{
int i = 0;
foreach (Person person in Model.Department.Persons)
{
int j = 0;
foreach (var group in person.GroupPerDay)
{
<div class = "col-auto">
<input type = "text" hidden readonly asp-for = "Department.Persons[i].PersonId" value = "@Model.Department.Persons[i].PersonId" />
<input type = "text" hidden readonly asp-for = "Department.Persons[i].Name" value = "@Model.Department.Persons[i].Name" />
<input type = "text" hidden readonly asp-for = "Department.Persons[i].GroupPerDay[j].Id" value = "@Model.Department.Persons[i].GroupPerDay[j].Id" />
</div>
if (j == person.GroupPerDay.Count - 1)
{
<div class = "row">
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext" asp-for = "Department.Persons[i].GroupPerDay[j].Person.Name" value = "@Model.Department.Persons[i].GroupPerDay[j].Person.Name" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[j].Set1" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[j].Set2" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[j].Set3" />
</div>
</div>
}
else
{
<div class = "col-auto">
<input type = "hidden" asp-for = "Department.Persons[i].GroupPerDay[j].Set1" />
<input type = "hidden" asp-for = "Department.Persons[i].GroupPerDay[j].Set2" />
<input type = "hidden" asp-for = "Department.Persons[i].GroupPerDay[j].Set3" />
<input type = "hidden" asp-for = "Department.Persons[i].GroupPerDay[j].Person.Name" />
</div>
}
j++;
}
i++;
}
}
<div class = "row g-3 align-items-center">
<div class = "col-auto">
<button class = "btn btn-primary" type = "submit">Submit</button>
</div>
<div class = "col-auto">
<a class = "btn btn-danger" asp-controller = "Home" asp-action = "Index">Cancel</a>
</div>
</div>
Если вы хотите, чтобы в действии публикации отображался только последний элемент Persons[i].GroupPerDay
, попробуйте это.
<form method = "post" asp-action = "Create" class = "row g-3">
<div class = "row g-3 align-items-center">
<div class = "row-cols-auto">
<input type = "text" hidden class = "form-control-plaintext" value = "@Model.Department.DepartmentId" asp-for = "Department.DepartmentId" />
</div>
</div>
<div class = "row g-3 align-items-center">
<div class = "col-auto">
<label for = "SubDate" class = "col-form-label">NGÀY ĐĂNG KÝ: </label>
</div>
<div class = "col-auto">
<input type = "date" id = "SubDate" asp-for = "DayGroup.SubcriptionDate" class = "form-control" />
<span asp-validation-for = "DayGroup.SubcriptionDate" class = "text-dark"></span>
</div>
</div>
<div class = "mb-3 row">
<div class = "col-sm-3">
<input type = "text" readonly class = "form-control-plaintext" value = "DS HỌ TÊN" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 1" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 2" />
</div>
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext text-center" value = "CA 3" />
</div>
</div>
@for (int i = 0; i < Model.Department.Persons.Count; i++)
{
int j = Model.Department.Persons[i].GroupPerDay.Count - 1;
int firstIndex = 0;
<div class = "col-auto">
<input type = "text" hidden readonly asp-for = "Department.Persons[i].PersonId" value = "@Model.Department.Persons[i].PersonId" />
<input type = "text" hidden readonly asp-for = "Department.Persons[i].Name" value = "@Model.Department.Persons[i].Name" />
<input type = "text" hidden readonly asp-for = "Department.Persons[i].GroupPerDay[firstIndex].Id" value = "@Model.Department.Persons[i].GroupPerDay[j].Id" />
</div>
<div class = "row">
<div class = "col">
<input type = "text" readonly class = "form-control-plaintext" asp-for = "Department.Persons[i].GroupPerDay[firstIndex].Person.Name" value = "@Model.Department.Persons[i].GroupPerDay[j].Person.Name" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[firstIndex].Set1" value = "@Model.Department.Persons[i].GroupPerDay[j].Set1" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[firstIndex].Set2" value = "@Model.Department.Persons[i].GroupPerDay[j].Set2" />
</div>
<div class = "col">
<input type = "number" class = "form-control" asp-for = "Department.Persons[i].GroupPerDay[firstIndex].Set3" value = "@Model.Department.Persons[i].GroupPerDay[j].Set3" />
</div>
</div>
}
<div class = "row g-3 align-items-center">
<div class = "col-auto">
<button class = "btn btn-primary" type = "submit">Submit</button>
</div>
<div class = "col-auto">
<a class = "btn btn-danger" asp-controller = "Home" asp-action = "Index">Cancel</a>
</div>
</div>
Передача коллекций данных становится чертовски запутанной. Для начала используйте инструменты отладчика в вашем браузере, чтобы фактически захватить форму POST и проверить данные формы. MVC попытается составить класс модели представления из любых деталей, поступающих из полей данных формы, которые извлекаются из распознанных элементов на странице. Это часто означает, что прежде чем он сможет повторно увлажнять дочерние элементы коллекции, у каждого дочернего элемента должно быть достаточно признанных свойств. (т. е. скрытые входные данные для не отображаемых значений). Я также не рекомендую смешивать объекты с моделями представлений.