簡體   English   中英

比較從c#中的ToArray()方法返回的字符串值

[英]comparing a string value returned from ToArray() method in c#

以下是我編寫的代碼,用於通過廣告表中的名稱搜索特定項目。

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

即使我搜索數據庫中已經存在的項目,在所有情況下,if條件都不成立。每次,我都會在視圖頁面中獲得整個項目列表。 這是什么問題?

我的廣告模型如下所示。

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

我想你應該做這樣的事情

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

此代碼將獲取與我們的支票(Title == name)匹配的第一項(如果存在)並返回它。 如果找不到符合條件的內容,它將返回一個名為“ Notfound”的視圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM