2013-10-06 74 views
0

以下是由我编写的用于在广告表中按名称搜索特定项目的代码。比较从C#中的ToArray()方法返回的字符串值。

public ActionResult SearchResult(string name) 
{ 
    var advertisement = db.Advertisements.ToArray(); // retrieve data from database 
    foreach (var ad in advertisement) 
    { 
     if (ad.Title.Equals(name)) 
     { 
      return View(ad); 
     } 
    } 

    return View(advertisement); 
} 

即使我搜索的是已经在数据库中,在所有情况下,如果条件不被true.Each时间,我得到的物品作为结果在视图首页的整个列表中的项目。这里有什么问题?

我的广告模型看起来像这样。

using System; 
using System.Drawing; // Image type is in this namespace 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; 

namespace Bartering.Models 
{ 
    public class Advertisement 
    { 
     [Key] 
     public int ID { get; set; } 

     [Required] 
     [StringLength(100)] 
     public string Title { get; set; } 

     public Guid OwnerID { get; set; } 

     [Required] 
     public string Category { get; set; } 

     public byte[] Image { get; set; } 

     [Required] 
     [StringLength(200)] 
     public string Description { get; set; } 
    } 
} 
+1

那么你有没有通过调试来验证你确实得到了预期的对象?你有没有检查过你是否正确接收了'name'? –

+1

用'StringComparison.InvariantCultureIgnoreCase'尝试用忽略 – Satpal

+0

@JonSkeet我试过调试,而且令人惊讶的是name的值为空 – DesirePRG

回答

0

,我认为你应该做这样的

public ActionResult SearchResult(string name) 
{ 
    var ad=db.Advertisements.Where(s=>s.Title.ToUpper()==name.ToUpper()) 
        .FirstOrDefault(); 
    if(ad!=null) 
     return View(ad); 
    //Nothing found for search for the name, Let's return the "NotFound" view 
    return View("NotFound"); 
} 

这个代码的东西将获得的第一项(如果存在),它与我们的检查(标题==名称),并返回它匹配。如果没有找到与条件匹配的任何东西,它将返回一个名为“Not Found”的视图。

+0

我试过这个,它将路由到未发现的视图,即使当我搜索已经在数据库中的项时 – DesirePRG

+1

把视觉你的方法中的工作室断点,看看你在'db.Adverisements'集合中得到了什么,看看你是否有一个Title属性值匹配你的'name'变量值的条目 – Shyju

+0

即使你的代码和我的代码名字也是null – DesirePRG

相关问题