Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to Ajax coll Database in MVC C#

New member
Joined
Feb 14, 2023
Messages
7
How to link between AJAX, Database and Controller in an MVC project It works as a drop down list and the results can be searched through this drop down list
I tried writing the code in Ajax and MVC, and it is expected to create a search list similar to Google, in which I enter some letters and it completes the sentences according to the existing database
 
New member
Joined
Feb 14, 2023
Messages
10
Ok, I think that you already have a DbContext and can retrieve your entities from it.

So you need to create a controller action that returns a result as JSON. This action will handle the AJAX request from the client-side and return the search results as JSON data.

Code:
public class SomeEntityController : Controller
{
    private readonly MyDbContext _context;

    public SomeEntityController(MyDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public JsonResult Search(string term)
    {
        var results = _context
            .SomeEntities
            .Where(e => e.Name.Contains(term))
            .Select(e => new { id = e.Id, text = e.Name })
            .ToList();

        return Json(results);
    }
}
Then create a view with a dropdown list and some JavaScript code to handle the AJAX request:
 
Top