I'm trying to figure out one of package in ASP.Net MVC 5 called MVC.Grid.
I have model like below :
public class MasterCustomer
{
public System.Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
And controller like this :
public class MasterCustomersController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: MasterCustomers
public ActionResult Index()
{
if (HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
return PartialView("_IndexGrid", db.MasterCustomers.ToList());
return View(db.MasterCustomers.ToList());
}
[HttpGet]
public PartialViewResult IndexGrid(String search)
{
return PartialView("_IndexGrid", db.MasterCustomers.Find(search));
}
}
I want to separate this into two questions:
How this controller works, when I do sort or search, it returns correctly even there is no controller handle for the action. Example :
http://localhost/MasterCustomers?search=&sort=code&order=asc&_=1533109639307
http://localhost/MasterCustomers?search=&sort=code&order=asc&code-contains=tes&code-op=&code-contains=&_=1533109639308
even there is no sort
and order
or contains
action in my controller, this action working nicely.
sadly one of GlobalSearch action search
didn't work correctly. It returns all data no matter what I typed. Example :
http://localhost/MasterCustomers?search=sdfasdfasdfasdfsadwrh2w3rwegaweg&_=1533109639344
If I know how question in no. 1 works maybe I can figure out the question in no.2.
The full source code is available for this Open Source Project, so if you have some patience, you could find out yourself. Basically, by executing Html.Grid(Model)
in the View, a new HtmlGrid
is constructed, which has raw access to your query parameters:
grid.Query = new NameValueCollection(grid.ViewContext.HttpContext.Request.QueryString);
so these don't have to be Route Attributes.
Your Ajax Check ("if (HttpContext.Request.Headers["X-...
") appears to be incorrect, where did you get that from? The implementation example on the page you provided is clearly different. By calling Index
instead of IndexGrid
as it's supposed to be, you lose the search parameter
Change your index
to :
public ActionResult Index()
{
return View();
}
and IndexGrid
to :
[HttpGet]
public PartialViewResult IndexGrid(String search)
{
if (String.IsNullOrEmpty(search))
return PartialView("_IndexGrid", db.MasterCustomers.ToList());
else
return PartialView("_IndexGrid", db.MasterCustomers.Where(x => x.Code.Contains(search) || x.Name.Contains(search)).ToList());
}