locked
Razor table add/remove data RRS feed

  • Question

  • User-1104215994 posted

    Hi,

    I have a cshtml page as follows:

    <form class="needs-validation" novalidate>
        <div class="container-fluid">
    
    
    
            <div class="row">
    
    
                <div class="col-md-6">
    
                    <div class="row">
    
                        <div class="col-md-4">
    
                        </div>
    
                        <div class="form-group col-md-5 input-group">
                            <select class="custom-select" id="validationCustom04" required>
                                <option selected disabled value="">Choose...</option>
                                <option value="ZULA">ZULA - 5TL</option>
                                <option value="STEAM">STEAM - 10TL</option>
                                <option value="GameForge">Gameforge - 6TL</option>
                                <option value="PUBG">PUBG Mobile - 10TL</option>
                                <option value="LOL">League of Legends - 12TL</option>
                            </select>
                            <div class="invalid-feedback">
                                Please select a game.
                            </div>
    
    
                        </div>
    
                    </div>
    
                    <div class="row">
    
                        <div class="col-md-4">
    
                        </div>
    
                        <div class="form-group col-md-5 input-group">
    
                            <div class="input-group-prepend">
                                <span class="input-group-text" id="basic-addon1">Quantity</span>
                            </div>
                            <input type="number" class="form-control " id="quantity" name="Quantity" value="1" aria-describedby="basic-addon1" />
    
                        </div>
    
                    </div>
    
                    <div class="row">
    
                        <div class="col-md-4">
    
                        </div>
    
                        <div class="form-group col-md-5 input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text" id="basic-addon2">E-mail&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            </div>
    
                            <input type="email" class="form-control" aria-describedby="basic-addon2" required id="email"/>
                            <div class="invalid-feedback">
                                Please provide a valid email.
                            </div>
                        </div>
    
    
    
                    </div>
    
                    <div class="row">
    
                        <div class="col-md-4">
    
                        </div>
    
                        <div class="form-group col-md-5">
    
                            <input id="btn_purchase" type="submit" value="Purchase" class="btn btn-success" />
                            <input id="btn_clear" type="button" value="Clear" class="btn btn-warning" />
    
                        </div>
    
                    </div>
    
                </div>
                
                <div class="col-md-5">
                    
                    <div class="form-group col-md-5">
                        <h3>Serials</h3>
                       
                        <textarea class="form-control" id="result" rows="5" readonly=""></textarea>
                    </div>
    
                </div>
    
            </div>
    
        </div>
    
    </form>

    I would like to add a table and a button (add). If the user clicks the add button, I would like to add data from inputs above to the table. In the table in each row, there should be a remove button in order to remove the selected row. Is there any tutorial that I can follow.

    Best Regards.

    Thursday, March 12, 2020 7:51 AM

Answers

  • User711641945 posted

    Hi cenk1536,

    As mgebhard said,you could try to use Bootstrap Modal.Here is a simple demo like below:

    1.Model:

    public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    2.Index.cshtml:

    @model IEnumerable<Test>
    
    <h1>Index</h1>
    
    <p>
        <button type="button" id="create" class="btn btn-primary" >
            Create New
        </button>
    </p>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        <input type="button" id="delete" value="Delete" class="btn btn-primary" onclick="DelteItem(@item.Id)" />
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <div class="modal fade" id="CreateModal" role="dialog"></div>
    <div class="modal fade" id="DeleteModal" role="dialog"></div>
    @section Scripts
    {
        <script>
        $(function () {
                $('#create').click(function () {
                    $.ajax({
                        url:"/Tests/Create",
                        type: "GET",
                        dataType: "html",
                        success: function (data) {
                            console.log(data);
                            $('#CreateModal').html(data);
                            $('#CreateModal').modal('show');
                        }
                    })
                })
        });
            function DelteItem(id) {
                $.ajax({
                            url: "/Tests/Delete/" + id,
                            type: "GET",
                            dataType: "html",
                            success: function (data) {
                                console.log(data);
                                $('#DeleteModal').html(data);
                                $('#DeleteModal').modal('show');
                            }
                        })
            }
        </script>
    }

    3.Create.cshtml:

    @model Test
    
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form asp-action="Create">
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                    <div class="form-group">
                        <label asp-for="Name" class="control-label"></label>
                        <input asp-for="Name" class="form-control" />
                        <span asp-validation-for="Name" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" value="Create" class="btn btn-primary" />
                    </div>
    
                </form>
            </div>
        </div>
    </div>
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

    4.Delete.cshtml:

    @model Test
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h3>Are you sure you want to delete this?</h3>
                <div>
                    <dl class="row">
                        <dt class="col-sm-2">
                            @Html.DisplayNameFor(model => model.Name)
                        </dt>
                        <dd class="col-sm-10">
                            @Html.DisplayFor(model => model.Name)
                        </dd>
                    </dl>
    
                    <form asp-action="Delete">
                        <input type="hidden" asp-for="Id" />
                        <div class="form-group">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <input type="submit" value="Delete" class="btn btn-primary" />
                        </div>                   
                    </form>
                </div>
            </div>
    
        </div>
    </div>

    5.Controller:

    public class TestsController : Controller
    {
        private readonly YourContext _context;
    
        public TestsController(YourContext context)
        {
            _context = context;
        }
    
        // GET: Tests
        public async Task<IActionResult> Index()
        {
            return View(await _context.Test.ToListAsync());
        }
    
        // GET: Tests/Create
        public IActionResult Create()
        {
            return View();
        }
    
        // POST: Tests/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name")] Test test)
        {
            if (ModelState.IsValid)
            {
                _context.Add(test);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(test);
        }      
        // GET: Tests/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
    
            var test = await _context.Test
                .FirstOrDefaultAsync(m => m.Id == id);
            if (test == null)
            {
                return NotFound();
            }
    
            return View(test);
        }
    
        // POST: Tests/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var test = await _context.Test.FindAsync(id);
            _context.Test.Remove(test);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 13, 2020 2:38 AM

All replies

  • User711641945 posted

    Hi cenk1536,

    I suggest that you could refer to the MVC or Razor Pages' official document:

    Get started with ASP.NET Core MVC

    Get started with Razor Pages in ASP.NET Core

    Result:

    Best Regards,

    Rena

    Thursday, March 12, 2020 9:39 AM
  • User-1104215994 posted

    Thank you, I want to have the table on the same page.

    Thursday, March 12, 2020 11:17 AM
  • User475983607 posted

    Thank you, I want to have the table on the same page.

    I assume you want the table and edit UI on the same page?  If so, use a modal. 

    See the Bootstrap official documentation which illustrates a pattern for populating model HTML using basic jQuery. 

    https://getbootstrap.com/docs/4.0/components/modal/

    The server logic will follow the Getting Started tutorial the only change is you need to write a little jQuery/JavaScript which, again, is outlined in the Bootstrap docs.

    Thursday, March 12, 2020 11:51 AM
  • User711641945 posted

    Hi cenk1536,

    As mgebhard said,you could try to use Bootstrap Modal.Here is a simple demo like below:

    1.Model:

    public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    2.Index.cshtml:

    @model IEnumerable<Test>
    
    <h1>Index</h1>
    
    <p>
        <button type="button" id="create" class="btn btn-primary" >
            Create New
        </button>
    </p>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        <input type="button" id="delete" value="Delete" class="btn btn-primary" onclick="DelteItem(@item.Id)" />
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <div class="modal fade" id="CreateModal" role="dialog"></div>
    <div class="modal fade" id="DeleteModal" role="dialog"></div>
    @section Scripts
    {
        <script>
        $(function () {
                $('#create').click(function () {
                    $.ajax({
                        url:"/Tests/Create",
                        type: "GET",
                        dataType: "html",
                        success: function (data) {
                            console.log(data);
                            $('#CreateModal').html(data);
                            $('#CreateModal').modal('show');
                        }
                    })
                })
        });
            function DelteItem(id) {
                $.ajax({
                            url: "/Tests/Delete/" + id,
                            type: "GET",
                            dataType: "html",
                            success: function (data) {
                                console.log(data);
                                $('#DeleteModal').html(data);
                                $('#DeleteModal').modal('show');
                            }
                        })
            }
        </script>
    }

    3.Create.cshtml:

    @model Test
    
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form asp-action="Create">
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                    <div class="form-group">
                        <label asp-for="Name" class="control-label"></label>
                        <input asp-for="Name" class="form-control" />
                        <span asp-validation-for="Name" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" value="Create" class="btn btn-primary" />
                    </div>
    
                </form>
            </div>
        </div>
    </div>
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

    4.Delete.cshtml:

    @model Test
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h3>Are you sure you want to delete this?</h3>
                <div>
                    <dl class="row">
                        <dt class="col-sm-2">
                            @Html.DisplayNameFor(model => model.Name)
                        </dt>
                        <dd class="col-sm-10">
                            @Html.DisplayFor(model => model.Name)
                        </dd>
                    </dl>
    
                    <form asp-action="Delete">
                        <input type="hidden" asp-for="Id" />
                        <div class="form-group">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <input type="submit" value="Delete" class="btn btn-primary" />
                        </div>                   
                    </form>
                </div>
            </div>
    
        </div>
    </div>

    5.Controller:

    public class TestsController : Controller
    {
        private readonly YourContext _context;
    
        public TestsController(YourContext context)
        {
            _context = context;
        }
    
        // GET: Tests
        public async Task<IActionResult> Index()
        {
            return View(await _context.Test.ToListAsync());
        }
    
        // GET: Tests/Create
        public IActionResult Create()
        {
            return View();
        }
    
        // POST: Tests/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name")] Test test)
        {
            if (ModelState.IsValid)
            {
                _context.Add(test);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(test);
        }      
        // GET: Tests/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
    
            var test = await _context.Test
                .FirstOrDefaultAsync(m => m.Id == id);
            if (test == null)
            {
                return NotFound();
            }
    
            return View(test);
        }
    
        // POST: Tests/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var test = await _context.Test.FindAsync(id);
            _context.Test.Remove(test);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 13, 2020 2:38 AM