skip to Main Content

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; }
}

Error Image


Thank you

2

Answers


  1. Your model is set up to capture only a single string value for CollectionCategory. Change CollectionCategory in your PostModel to a List<string> to store multiple selected categories.

    public class PostModel
    {
        // Other properties before
    
        public List<string>? CollectionCategories { get; set; }
    }
    

    Update the CreatePostViewModel to use List<string> for CollectionCategory:

    public class CreatePostViewModel
    {
        // Other properties before
    
        // Category
        public List<string>? CollectionCategory { get; set; }
    
        // Category List
        public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
    }
    
    Login or Signup to reply.
  2. To save multiple checkbox value ,

    PostModel

    public class PostModel
    {
        // Code before
    
          public List< string>? CollectionCategory { get; set; }
    }
    

    CreatePostViewModel

    public class CreatePostViewModel
    {
        public  List<string>? CollectionCategory { get; set; }
    
        // Category List
        public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
    }
    

    in the view you can try:

        @for (var i = 0; i < Model.CollectionCategoryList.Count; i++)
      {
          <input type="checkbox" name="CollectionCategory[@i]" id="CollectionCategoryList[@i].CategoryName" value="@Model.CollectionCategoryList[@i].CategoryName">
          <label asp-for="CollectionCategory" for="Model.CollectionCategoryList[@i].CategoryName"> @Model.CollectionCategoryList[@i].CategoryName </label>
      }
    

    result:

    enter image description here

    Update:

    public class PostModel
    {
        // Code before
    
        public string? CollectionCategory { get; set; }
    }
    

    Then in your create :

    [HttpPost]
    public async Task<IActionResult> Create(CreatePostViewModel postVM)
    {
        if (ModelState.IsValid)
        {
           for(var i=0;i< postVM.CollectionCategory.Count; i++)
    {
        var post = new PostModel
        {
            // Code before             
    
            // Category
            CollectionCategory = postVM.CollectionCategory[i],
        };
           _context.Add(post); 
          await _context.SaveChangesAsync();
    }
    
             return RedirectToAction("Index");
        }
        else
        {
            // Error
        }
        return View(postVM);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search