以下是由我编写的用于在广告表中按名称搜索特定项目的代码。比较从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; }
}
}
那么你有没有通过调试来验证你确实得到了预期的对象?你有没有检查过你是否正确接收了'name'? –
用'StringComparison.InvariantCultureIgnoreCase'尝试用忽略 – Satpal
@JonSkeet我试过调试,而且令人惊讶的是name的值为空 – DesirePRG