簡體   English   中英

ASP.NET MVC C#搜索幫助

[英]ASP.NET MVC C# Search help

我的HomeController.cs中有以下代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MyApplication.Models;

namespace MyApplication.Controllers
{
    public class HomeController : Controller
    {
        private NewsDBEntities _db = new NewsDBEntities();

        //
        // GET: /Home/

        public ActionResult Index()
        {

            return View(_db.ArticleSet.ToList());

        }

        //
        // GET: /Home/Details/5

        public ActionResult Details(int id)
        {
            //return View();

            var ArticleToView = (from m in _db.ArticleSet

                               where m.storyId == id

                               select m).First();

            return View(ArticleToView);
        }



        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(String query)
        {

            var ArticleQuery = (from m in _db.ArticleSet

                                where m.headline.Contains(query)

                                select m).First();

            return View(ArticleQuery);

            //return RedirectToAction("Search");

        }

    }
}

在Home / Index.aspx下的views文件夾中,有一個簡單的搜索表單,如下所示:

    <% using (Html.BeginForm()) {%>

        <fieldset>
            <legend>Search</legend>
            <p>
                <label for="query">Keywords:</label>
                <%= Html.TextBox("query") %>
            </p>
            <p>
                <input type="submit" value="Search" />
            </p>
        </fieldset>

    <% } %>

想法是,當用戶提交此表單時,將使用查詢文本框的內容,然后對照來自我的數據庫的文章的標題進行檢查,並且“索引”視圖將不顯示所有文章,而只會顯示匹配的文章用戶鍵入的查詢。

提交表單時,出現以下錯誤:

The model item passed into the dictionary is of type 'MyApplication.Models.Article' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MyApplication.Models.Article]'. 

我在這里做錯了什么? 從我可以看出的代碼是好的。

似乎在您的View中,您具有Inherits="System.Web.Mvc.ViewPage<IEnumerable<Article>>"但您只傳遞了一個。 可以將IEnumerable替換為單個IEnumerable ,或者擺脫.First()

您的視圖已強烈鍵入MyApplication.Models.Article的集合。 您不能將單個MyApplication.Models.Article傳遞到視圖中。

傳遞給的視圖是'System.Collections.Generic.IEnumerable1[MyApplication.Models.Article]'的強類型視圖。 更改視圖的類型,或將IEnumerable的Articles集合傳遞給視圖。

如何顯示搜索后返回的文章數以及查詢的內容。 並根據用戶是否進行搜索來隱藏和顯示它。

我建議使用自定義視圖模型向視圖提供所有必要的信息以呈現給用戶。

public class SearchResultViewModel {
   public IEnumerable<MyApplication.Models.Article> Articles { get; set; }
   public string SearchText { get; set; }
}

在您的控制器中,您將創建此模型的新實例,並相應地填充它。

然后,將您的視圖強烈鍵入SearchResultViewModel ,並在需要的地方使用它:

  1. 結果計數: <%: Model.Articles.Count() %>
  2. 搜索文本: <%: Model.SearchText %>

暫無
暫無

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

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