skip to Main Content

I was able to create CRUD operations with searching and paging in ASP.NET MVC using Entity Framework, now I want to use Ajax for searching and paging.

What would be the steps to create it?

Here is my code:

CustomerController

using MvcCRUDSearching.Models;
using PagedList;

namespace MvcCRUDSearching.Controllers
{
    public class CustomerController : Controller
    {
        // GET: Customer
        public ActionResult Index(string searchBy, string searchString, int? page)
        {
            using (DbModels dbModel = new DbModels())
            {
                if (searchBy == "Department")
                {
                    IPagedList<Customer> dep = dbModel.Customers.Where(x => x.Department == searchString || searchString == null).ToList().ToPagedList(page ?? 1, 2);
                    return View(dep);
                }
                else if (searchBy == "Name")
                {
                    IPagedList<Customer>  nam = dbModel.Customers.Where(y => y.Name.StartsWith(searchString) || searchString == null).ToList().ToPagedList(page ?? 1, 2);
                    return View(nam);
                }
                else
                {
                    return View(dbModel.Customers.ToList().ToPagedList(page ?? 1, 2));
                }
            }
        }
    }
}

Index.cshtml

@using MvcCRUDSearching.Models;
@using PagedList.Mvc;
@using PagedList;
@model IPagedList<MvcCRUDSearching.Models.Customer>

@{
    ViewBag.Title = "Index";
}

<div id="div1">
    <h2>Index</h2>

    <p>
        @Html.ActionLink("Create New", "Create")
    </p>

    <p>
        @using (@Html.BeginForm("Index", "Customer", FormMethod.Get))
        {
            <b> Search By:</b>
            @Html.RadioButton("searchBy", "Name", true)<text>Name</text>
            @Html.RadioButton("searchBy", "Department")<text>Department</text>
            @Html.TextBox("searchString") <input type="submit" value="Search" class="btn" />
        }
    </p>

    <table class="table">
        <tr>
            <th>
                Name
            </th>
            <th>
                Department
            </th>
            <th>Action</th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Department)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                    @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.ID })
                </td>
            </tr>
        }

    </table>
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page, searchBy = Request.QueryString["searchBy"], search = Request.QueryString["searchBy"] }))
</div>

I only know that I need a partial view, but for what and where should I place it?

~/Views/Shared

or

~/Views/Customer

Sorry for this long questions, but I’m a little green.

2

Answers


  1. Not entirely sure if this will help you but it seems like it would be a bit of a different approach to what you’re taking.

    I built something similar recently and used DataTables

    once the user has supplied the search by data you can do a simple ajax call and then repopulate the table:

    JS:

    var data = JSON.stringify({
                    'Searchby': '',
                    'SearchString': ''
                })
    $.ajax({
                type: 'POST',
                url: '/Cutomers/GetCustomers',
                data: data,
                contentType: 'application/json',
                dataType: 'json',
                success: function (result) {
                    var table = $('#TableID').DataTable();
                    table.destroy();
                    var table = $('#TableID').DataTable({
                        responsive: true,
                        "scrollY":true,
                        "scrollX":true,
                        "data": result,
                        "columns": [
                            { "data": "Name" },
                            { "data": "Department" },
    
                        ]
    
    
                    });
                    $('#divResults').show();
    
    
    
                }
    

    HTML:

    <div class="centerContainer">
    <div class="main row">
        <div id="divResults">
            <table id="TableID" class="table">
                <thead>
                    <tr>
    
                        <th></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="table"></tbody>
            </table>
    
        </div>
    
    
    </div>
    

    This is probably not the best practice but it works really well and handles pagination for you.

    Login or Signup to reply.
  2. Based on your solution, you should put _ListPartialView into Individual view folder, and create a ListItemViewModel

    public class ListItemViewModel
    {
      public string ID{get;set;}
      public string Name{get;set;}
      public string DepartName{get;set;}
    }
    

    then try to build _ListPartialView,

    @model IList<ListItemViewModel>
    <!---->
    <table class="table">
        <tr>
            <th>
                Name
            </th>
            <th>
                Department
            </th>
            <th>Action</th>
        </tr>
    
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    item.Name
                </td>
                <td>
                    item.Department
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                    @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.ID })
                </td>
            </tr>
        }
    
    </table>
    

    after that use ajax call in main page to load partial view.

    or you can try jQuery datatable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search