Search code examples
c#asp.netasp.net-mvc-4entity-framework-4ef-code-first

ASP.NET MVC 4 searching from existing database


I was wondering if anyone could help me with making a datacontext on existing database and searching from it.

What i've done so far:

  1. Made connectionstring for existing database on web.config (same name as my newly created DataContext class)
  2. Made DataContext class, and model class for it where are the fields i want to get.
  3. Made controller for it which calls for the search
  4. Made view for the controller

Here is the code i've used.

DataContext class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace KendoUIMvcCim.Models
{
    public class CustDataContext : DbContext
    {
        public DbSet<Contacts> CLIENT { get; set; }

    }
}

Model class for the information i want to search

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace KendoUIMvcCim.Models
{
    public class Contacts
    {
        [Key]
        public int CLIENT_ID { get; set; }
        public string FIRSTNAME { get; set; }
        public string LASTNAME { get; set; }
        public string TEL_TEL1 { get; set; }
        public string TEL_TEL2 { get; set; }
        public string TEL_GSM { get; set; }
    }
}

Controller

public ActionResult Testi(int? clientid)
        {
            using (var db = new CustDataContext()) 
         {
           var contact = db.CLIENT.Find(clientid);

             if (contact != null)
             {
                 return View(contact);
             }
             else
             {
                 return RedirectToAction("Index", "Customer");
             }

         }

Any help would be appreciated!

Best regards, Eero


Solution

  • Use Linq like this:

        public ActionResult Index(string searchTerm = null)
        {
    
            var model =
                _db.Clients
                .Where(r => searchTerm == null || r.FirstName.StartsWith(searchTerm) || r.LastName.StartsWith(searchTerm))
                    .Take(10)
                    .Select r;
    
            return View(model);
        }
    

    Index view could be like this:

    @model IEnumerable<AppName.Models.ModelName>
    
    @{
       ViewBag.Title = "Home Page";
    }
    
    <form method="GET">
        <input type="search" name="searchTerm" />
        <input type="submit" value="Search for a name"/>
    </form>
    @try
    {
        foreach (var item in Model)
        {
            <h3>@Html.DisplayFor(modelItem => item.FirstName)</h3>
            <p>@Html.DisplayFor(modelItem => item.LastName)</p>
    
        }
    }
    catch (NullReferenceException nullex)
    {
        <p>@nullex</p>
    }