How to insert multiple textbox data together in Asp.net Core

jewel 1,186 Reputation points
2023-08-12T08:26:19.8466667+00:00

I have two tables. One product is another purchases. I want to do a task where two more columns will be added to the product table along with the data. One is checkbox and another textbox. If I enter a number in the textbox of the products to be purchased, the checkbox of this row will be checked. And simultaneously, many products will be inserted into the database at the click of a button. Only values ​​in the textbox will be inserted. Null values ​​will not be inserted.

//Models
namespace aspCoreProject.Models
{
    public class tbl_purchase
    {
        [Key]
        public int PurchaseID { get; set; }
        public int ProductID { get; set; }
        public int Qty { get; set; }
    }
}
//Models
namespace aspCoreProject.Models
{
    public class tbl_Product
    {
        [Key]
        public int ProductID { get; set; }
        public String ProductName { get; set; }
        public Decimal PurchaseRate { get; set; }
    }
}
//Controllers 
namespace aspCoreProject.Controllers 
{public class PurchaseController : Controller
{private ApplicationDbContext _context; 
public PurchaseController(ApplicationDbContext context)         
{_context = context;}         
public IActionResult Index()         
{var List = _context.tbl_Products.ToList();             
return View(List);  
                   }     
} 
}
//Index.cshtml
@model IEnumerable<aspCoreProject.Models.tbl_Product> 
<button class="btn btn-primary">save Data</button>  	
<table class="table table-bordered"> 		
<tr> 		
<th><input type="checkbox"> Allproduct</th> 			
<th> ProductID </th> 		
<th> ProductName</th> 		
<th>PurchaseRate</th> 		
<th>Qty</th> 		
</tr> 	
@foreach (var item in Model) 
{<tr> 			
<td><input type="checkbox" name="check" class="check"></td> 			
<td>@item.ProductID</td> 			
<td>@item.ProductName</td> 			
<td>@item.PurchaseRate</td> 			
<td><input type="text" class="num" ></td> 		
</tr>} 	
</table> 	 
<script> 	
$(".num").on("keyup", function (e)
{if (this.value != "") 
{ $(".check").prop("checked", "checked");} 
else {$(".check").prop('checked', ""); 		
} 	
});  
</script> 

I don't know how this is possible in Asp.net Core.
If any experienced would help me. I would benefit. thanks in advance
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-08-14T03:00:31.21+00:00

    Hi @jewel

    You can create a ViewModel which contains the required properties to display in the page and then transfer them to the back end.

    For example, you can create a ProductVM like this:

        public class ProductVM //used to display the product with purchases and qty
        {
            public int ProductID { get; set; }
            public String ProductName { get; set; }
            public Decimal PurchaseRate { get; set; }
            public int Qty { get; set; }
            public bool IsChecked { get; set; }
        }
    

    Then, when you want to add the Purchases based on the Product, in the Get action method, you can query the Product table, and then in the select clause, you can convert the data to the view model. And in the Post method, you can use LINQ query statement to filter the data and convert the view model to the EF core entities, after that insert them into database. Code like this:

        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
    
            public ApplicationDbContext _dbContext { get; set; }
    
            public HomeController(ILogger<HomeController> logger, ApplicationDbContext applicationnDbContext)
            {
                _logger = logger;
                _dbContext=applicationnDbContext;
            }
            public IActionResult PurchaseIndex()
            {
                var items = _dbContext.Purchases
                    .GroupJoin(_dbContext.Products,
                        pur => pur.ProductID,
                        pro => pro.ProductID,
                        (pur, pro) => new { Pur = pur, Pro = pro })
                    .Select(c => new ProductVM()
                    {
                        ProductID = c.Pur.ProductID,
                        ProductName = c.Pro.FirstOrDefault().ProductName,
                        PurchaseRate = c.Pro.FirstOrDefault().PurchaseRate,
                        Qty = c.Pur.Qty
                    }).ToList();
    
                return View(items);
            }
            public IActionResult AddPurchases()
            {
                var list = _dbContext.Products
                            .Select(c => new ProductVM()
                            {
                                ProductID = c.ProductID,
                                ProductName = c.ProductName,
                                PurchaseRate = c.PurchaseRate
                            }).ToList();
                return View(list);
            }
            [HttpPost]
            public IActionResult AddPurchases(List<ProductVM> products )
            {
                if (ModelState.IsValid)
                {
                   var insertitems = products.Where(c=>c.IsChecked = true && c.Qty != 0).Select(c=> new tbl_purchase()
                   {
                        ProductID = c.ProductID,
                        Qty = c.Qty
                   }).ToList();
                    _dbContext.Purchases.AddRange(insertitems);
                    _dbContext.SaveChanges();
                    return RedirectToAction(nameof(PurchaseIndex));
                }
    
                return View( );
            }
    

    In the AddPurchases Index page:

    @model List<TestMVC.Models.ProductVM>
    
    @{
        ViewData["Title"] = "AddPurchases";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h1>AddPurchases</h1>
    
    <h4>ProductVM</h4>
    <hr />
    <div class="row">
        <div class="col-md-12">
            <form asp-action="AddPurchases">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div> 
                 <button type="submit"  class="btn btn-primary">save Data</button>
                <table class="table table-bordered">
                    <tr>
                        <th><input type="checkbox"> Allproduct</th>
                        <th> ProductID </th>
                        <th> ProductName</th>
                        <th>PurchaseRate</th>
                        <th>Qty</th>
                    </tr>
                    @for(var i = 0; i<Model.Count;i++)
                    {
                        <tr>
                            <td> <input asp-for="@Model[i].IsChecked" type="checkbox" id="chk_isChecked" /></td>
                            <td>@Model[i].ProductID <input asp-for="@Model[i].ProductID" type="hidden" class="form-control" /></td>
                            <td>@Model[i].ProductName <input asp-for="@Model[i].ProductName" type="hidden" class="form-control" /></td>
                            <td>@Model[i].PurchaseRate <input asp-for="@Model[i].PurchaseRate" type="hidden" class="form-control" /></td>
                            <td><input asp-for="@Model[i].Qty" class="form-control txt_qty" /></td>
                        </tr>
                    }
                </table>
            </form>
        </div>
    </div> 
    
    @section Scripts { 
        <script>
            $(function(){
                $(".txt_qty").each(function (index, item) {
                    var txtvalue = $(item).val();
                    if(txtvalue.length > 0 && txtvalue != "0"){
                        $(item).closest("tr").find("#chk_isChecked").prop('checked', true);
                    }
                    else{
                        $(item).closest("tr").find("#chk_isChecked").prop('checked', false);
                    }
                    $(item).change(function(){
                        var currentvalue = $(this).val();
                        if (currentvalue.length > 0 && currentvalue != "0") {
                            $(this).closest("tr").find("#chk_isChecked").prop('checked', true);
                        }
                        else {
                            $(this).closest("tr").find("#chk_isChecked").prop('checked', false);
                        }
                    })
                }) 
            })
        </script>
    
    }
    
    

    Finally, the result as below:

    image2


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.