I'm working in entityframework 6.
I have a problem with my Checkbox. I'm trying to select multiple of choices then save these choices to a List, save them to my PostModel which holds an ICollection<TagLogs>.
Like any other i scoured the net for a solution, and followed some, but to no answer.
I am getting this error:
InvalidOperationException: Unexpected 'asp-for' expression result type 'System.Collections.Generic.List`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' for . 'asp-for' must be of type 'System.Boolean' or 'System.String' that can be parsed as a 'System.Boolean' if 'type' is 'checkbox'. I understand i need to change the SelectedChanges and make it to a Boolean or a string, then change few other things, but i still got more errors.
[BindProperty]
public List<int> SelectedChanges { get; set; } = new List<int>();
public IEnumerable<TagLog> TagLogs { get; set; }
public async Task OnGet()
{
//ChangeLogs = changeLogRepository.GetAllModels();
TagLogs = await context.TagLogs.ToListAsync();
//SelectedChanges = new List<int>();
}
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
var newPost = context.PostModels.FirstOrDefault(p => p.Title == PostViewModel.Title);
if (newPost == null)
{
if (TagLogs != null)
{
var selectedType = TagLogs.Where(x => SelectedChanges.Contains(x.TagLogId)).ToList();
PostModel postModel = new PostModel
{
Title = PostViewModel.Title,
ChangeLogs = selectedType,
};
}
postRepository.Add(postModel);
TagLogs = changeLogRepository.GetAllModels();
}
return RedirectToPage("/Index");
}
return RedirectToPage("/Index");
}
FailedToPost = "Failed to Post, try again.";
return Page();
}
public class TagLog
{
[Key]
public int TagLogId { get; set; }
public string TagLogName { get; set; }
public bool IsChecked { get; set; }
public virtual ICollection<PostModel>? PostModels { get; set; }
}
Front End
@foreach (var change in Model.TagLogs)
{
<div class="form-check">
<!-- Set the value of the input to the change ID -->
<input class="form-check-input" type="checkbox" asp-for="SelectedChanges" value="@change.TagLogId" />
<label class="form-check-label">@change.TagLogName</label>
</div>
}
</div>
Best regards.
asp-forfor Lists. You have to use a boolean or a string property. There is a way to populate a list of checkboxes. But you need to create a separate viewmodel or a additional property in your existing models. Please see this post for more details: stackoverflow.com/questions/40555543/…Checked(if it is entity model you can add attributeNotMapped) on the modelTagLogand in your frontend you have to use for loop and then you can useasp-for="change[i].Checked"