How to use get method on ASP.NET MVC into datatable

Viewed 57

I'm new to ASP.NET MVC. I just know how to create more rows in a datatable.

I want to connect it with a database but can't figure out a way to do it.

I already create the controller, model and data class, and already finished Delete, Edit, Index methods.

I just need create method to finish the whole project.

I appreciate every answer to my question.

var table = null;
var arrData = [];
var arrDataPG = [];
arrData.push({
    STT: 1,
    id: 1,
    product_type: "",
    condition1: "",
});
$(document).ready(function () {
    InitTable();
});

function InitTable() {
    if (table !== null && table !== undefined) {
        table.destroy();
    }
    table = $('#tableh').DataTable({
        data: arrData,
        "columns": [
            { "width": "25px" },
            { "width": "300px" },
            { "width": "300px" },
            { "width": "25px" },


        ],
        columnDefs: [
            {
                title: "STT",
                targets: 0,
                data: null,
                render: function (data, type, row, meta) {
                    return (meta.row + meta.settings._iDisplayStart + 1);
                },
            },
            {
                title: "Loại sản phẩm*",
                targets: 1,
                data: null,
                render: function (data, type, row, meta) {
                    return '<textarea style="width: 300px;" id="product_type' + data.id + '" type="text" onchange="ChangeProductType(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.product_type + '">' + data.product_type + '</textarea>';
                }
            },
            {
                title: "Điều kiện*",
                targets: 2,
                data: null,
                render: function (data, type, row, meta) {
                    return '<textarea style="width: 300px;" id="condition1' + data.id + '" type="text" onchange="ChangeCondition1(\'' + data.id + '\',this)" name="' + data.id + '" value="' + data.condition1 + '">' + data.condition1 + '</textarea>';
                }
            },

            {
                title: "",
                targets: 3,
                data: null,
                className: "dt-center",
                width: "70",
                render: function (data, type, row, meta) {
                    // return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i style="cursor: pointer;font-size: 25px;padding-bottom: 30px;" class="fa fa-trash removePG" aria-hidden="true" onclick=removePG(\'' + data.id + '\')></i>';
                    return '<div class="btn btn-danger removePG" style="cursor: pointer;font-size:25px;" ><i class="fa-solid fa-trash"></i></div>';
                }
            },
        ],
    });
    table.columns.adjust().draw();
}

$('#addRow').on('click', function () {
    console.log(arrData.length);
    if (arrData != '') {
        var ida = arrData[0].id;
    } else {
        var ida = 1;
    }

    for (var i = 0; i < arrData.length; i++) {
        if (arrData[i].id > ida) {
            ida = arrData[i].id;
        }
    };
    arrData.push({
        STT: ida + 1,
        id: ida + 1,
        product_type: "",
        condition1: "",
    });
    if (table != null) {
        table.clear();
        table.rows.add(arrData).draw();
    }
});
$('#tableh').on('click', '.removePG', function () {
    var tableq = $('#tableh').DataTable();
    tableq
        .row($(this).parents('tr'))
        .remove()
        .draw();
});

 function removePG(idc) {
     let id = parseInt(idc);
     if (arrData !== undefined) {
         var find = arrData.find(function (item) {
             return item.id === id;
         });
        if (find !== undefined) {
            arrData = arrData.filter(function (item, index) {
               return item.id !== id;
            });
        };
    }
 }


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet"type="text/css"href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">

<table id="tableh" class="cell-border hover" style="width:100%"></table>
            
<button style="width: 86px;" id="addRow" class="btn btn-success add">Addrow<i class="fa fa-plus" aria-hidden="true"></i></button>

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<script src="https://kit.fontawesome.com/60bf89e922.js" crossorigin="anonymous"></script>

Here is my Controller and Model

using Microsoft.AspNetCore.Mvc;
using WebApplication1.Data;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
public class FirstrowController : Controller
{
    private readonly ApplicationDbContext _db;

    public FirstrowController(ApplicationDbContext db)
    {
        _db = db; 
    }

    public IActionResult Index()
    {
        IEnumerable<Firstrow> objFirstrowList = _db.Firstrow;
        return View(objFirstrowList);
    }


    //Get
    public IActionResult Create()
    {
        return View();
    }
    //POST
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Firstrow obj)
    {
        if (obj.product_type == obj.condition1.ToString())
        {
            ModelState.AddModelError("name", "Nhập thiếu kìa fen");
        }
        if (ModelState.IsValid) 
        {
            _db.Firstrow.Add(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(obj);
    }



    //Get
    public IActionResult Edit(int? id)
    {
        if (id == null || id == 0)
        {
            return NotFound();
        }
        var FirstrowFromDb = _db.Firstrow.Find(id);


        if (FirstrowFromDb == null)
        {
            return NotFound();
        }

        return View(FirstrowFromDb);
    }
    //POST
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Edit(Firstrow obj)
    {
        if (obj.product_type == obj.condition1.ToString())
        {
            ModelState.AddModelError("name", "Nhập thiếu kìa fen");
        }
        if (ModelState.IsValid)
        {
            _db.Firstrow.Update(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(obj);
    }


    //Get
    public IActionResult Delete(int? id)
    {
        if (id == null || id == 0)
        {
            return NotFound();
        }
        var FirstrowFromDb = _db.Firstrow.Find(id);


        if (FirstrowFromDb == null)
        {
            return NotFound();
        }

        return View(FirstrowFromDb);
    }
    //POST
    [HttpPost,ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public IActionResult DeletePOST(int? id)
    {
        var obj = _db.Firstrow.Find(id);
        if (obj == null) 
        {
            return NotFound();
        }
        _db.Firstrow.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");
    }
}

}

using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
public class Firstrow
{
    [Key]
    public int id { get; set; }
    [Required]
    public string product_type { get; set; }
    public string condition1 { get; set; }
   }
   }
1 Answers

Create a View Model that take care of all processes for all/remove/ saving to db and etc

 public class FirstRowVM
    {
        public List<FirstRow> FirstRows { get; set; }
        public string Command { get; set; }
        public int? Argument { get; set; }


        public FirstRowVM()
        {
            FirstRows = new List<FirstRow>();
            Command = "";
            Argument = null;
        }

        public void HandleRequest()
        {
            switch (Command)
            {
                case "Add":
                    AddRow();
                      break;

                case "Remove":
                    RemoveRow();
                    break;

                case "Save":
                    SaveRecord();
                    break;


                default:
                    break;
            }

        }

        private void AddRow()
        {
            FirstRow item = new FirstRow();
            FirstRows.Add(item);
        }

        private void RemoveRow()
        {
            int i = Convert.ToInt32(Argument);
            FirstRows.RemoveAt(i);
        }

        private void SaveRecord()
        {

        }
    }

This is you Controller Action. What it does is using the view to hold the data and also create command for delete/add action and etc.

 public class TestController :Controller
    {
        public FirstRowVM VM = new FirstRowVM();


        public ActionResult Create() 
        {

            return View(VM);
        }

        [HttpPost]
        public ActionResult Create(List<FirstRow> FirstRows, string Command, int? Argument)
        {
            ModelState.Clear();

            VM.FirstRows = FirstRows;
            VM.Command = Command;
            VM.Argument = Argument;

            if (VM.Command == "Save")
            {
                return RedirectToAction("Index");
            }
            else
            {
                VM.HandleRequest();
            }
            return View(VM);
        }

    }

This is the createView. Pay attention to the scripts. I am passing button property to get the command and argument to pass the action to the post method.

@model WorkshopPro.ViewModels.FirstRowVM

@{
    ViewBag.Title = "Create";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("Create", "Test", FormMethod.Post, new { id = "TransPost" }))
{
    @Html.HiddenFor(x => x.Argument)
     @Html.HiddenFor(x => x.Command)
<table class="table">
    <tr>
        <th>Product Type</th>
        <th>Condition</th>
        <th></th>
    </tr>

    @for (int i = 0; i < Model.FirstRows.Count(); i++)
    {
        <tr>
            <td>
                @Html.TextBoxFor(a => a.FirstRows[i].product_type,new{@value =Model.FirstRows[i].product_type })
            </td>
             <td>
                 @Html.TextBoxFor(a => a.FirstRows[i].condition1,new{@value =Model.FirstRows[i].condition1 })
            </td>
            <td>
                    <button id="Remove"
                    class="btn btn-sm btn-success"
                    data-pdsa-action="Remove"
                    data-pdsa-val = @i>
                        <i class="fa fa-trash"></i>
                        &nbsp;Remove
                    </button>
            </td>
        </tr>
    }
</table>

    <button id="AddRow"
        class="btn btn-sm btn-success"
        data-pdsa-action="Add">
        <i class="fa fa-add"></i>
        &nbsp;Add
    </button>
}




@section Scripts {
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    <script>
        $(document).ready(function () {
            $("[data-pdsa-action]").on("click", function (e) {
                
                e.preventDefault();

                $("#Command").val(
                    $(this).data("pdsa-action"));

                $("#Argument").val(
                    $(this).attr("data-pdsa-val"));

                var eventcommand = $(this).data("pdsa-action");

               

                if (eventcommand == 'DeleteAll') {
                    var x = confirm("Are you sure you want to delete?");
                    if (x)
                        document.getElementById("TransPost").submit();
                    else
                        return false;
                }
                else if (eventcommand == 'Cancel') {
                    var x = confirm("Are you sure you want to Cancel?");
                    if (x)
                        document.getElementById("TransPost").submit();
                    else
                        return false;
                }
                else if (eventcommand == 'SaveAll') {
                    var x = confirm("Do you wish to save the transaction?");
                    if (x)
                        document.getElementById("TransPost").submit();
                    else
                        return false;
                }
                else {
                    document.getElementById("TransPost").submit();
                }

            });
        });
    </script>
       
    
}
Related