I am using checkboxes to save data in database. It can save only one value at a time. When multiple values are selected, it only stores the first selected value.
I have Googled my problem. Multiple solutions suggested the use of List<string> Name
in Model. I tried to do so but my controller gave me error CS0029.
- Database Table (CollectionCategories):
Id | CategoryName |
---|---|
1 | First Category |
2 | Second Category |
… | … |
Code-
- Model:
public class PostModel
{
// Code before
public string? CollectionCategory { get; set; }
}
public class CollectionCategoryModel
{
[Key]
public int Id { get; set; }
public string CategoryName { get; set; }
}
- ViewModel:
public class CreatePostViewModel
{
// Code before
// Category
public string? CollectionCategory { get; set; }
// Category List
public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
}
- Controller:
public async Task<IActionResult> CreateAsync()
{
// Category List
var CreatePostCategoryVM = new CreatePostViewModel
{
CollectionCategoryList = await _context.CollectionCategories.ToListAsync()
};
return View(CreatePostCategoryVM);
}
[HttpPost]
public async Task<IActionResult> Create(CreatePostViewModel postVM)
{
if (ModelState.IsValid)
{
var post = new PostModel
{
// Code before
// Category
CollectionCategory = postVM.CollectionCategory,
};
return RedirectToAction("Index");
}
else
{
// Error
}
return View(postVM);
}
- View:
<div class="form-check">
@foreach (var list in Model.CollectionCategoryList)
{
<input type="checkbox" asp-for="CollectionCategory" id="@list.CategoryName" value="@list.CategoryName">
<label asp-for="CollectionCategory" for="@list.CategoryName"> @list.CategoryName </label>
}
</div>
Edited
Error:
(JsonReaderException: ‘S’ is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 1.)
- Controller
[HttpGet]
public async Task<IActionResult> Index()
{
var CardPostVM = new CardsViewModel
{
PostCard = await _context.Posts.ToListAsync()
};
var cached = _cache.TryGetValue("post", out var post);
if (cached)
{
return View(post);
}
return View(CardPostVM);
}
- ViewModel
public class CardsViewModel
{
public List<PostModel>? PostCard { get; set; }
public List<CollectionModel>? CollectionCard { get; set; }
}
Thank you
2
Answers
Your model is set up to capture only a single string value for
CollectionCategory
. ChangeCollectionCategory
in yourPostModel
to aList<string>
to store multiple selected categories.Update the
CreatePostViewModel
to useList<string>
forCollectionCategory
:To save multiple checkbox value ,
PostModel
CreatePostViewModel
in the view you can try:
result:
Update:
Then in your create :