繁体   English   中英

ASP.NET MVC 4 从现有数据库中搜索

[英]ASP.NET MVC 4 searching from existing database

我想知道是否有人可以帮助我在现有数据库上创建数据上下文并从中进行搜索。

到目前为止我所做的:

  1. 为 web.config 上的现有数据库创建连接字符串(与我新创建的 DataContext 类同名)
  2. 为它制作了 DataContext 类和模型类,我想获取的字段在哪里。
  3. 为它制作了要求搜索的控制器
  4. 为控制器制作视图

这是我使用过的代码。

数据上下文类

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; }

    }
}

我要搜索的信息的模型类

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; }
    }
}

控制器

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");
             }

         }

任何帮助,将不胜感激!

最好的问候,埃罗

像这样使用 Linq:

    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);
    }

索引视图可能是这样的:

@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>
}

在类型列表中搜索任何属性的通用方法

public static IEnumerable<T> SearchColumns<T>(this IEnumerable<T> obj, string searchkey)
        {
            var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);
            if (properties == null)
                throw new ArgumentException("{typeof(T).Name}' does not implement a public get property named '{key}.");
            var filteredObj = obj.Where(d => properties.Any(p => p.GetValue(d).ToString().Contains(searchkey))).ToList();
            return filteredObj;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM