c# - ASP.NET MVC C# 搜索帮助

标签 c# asp.net-mvc

我的 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 下的 View 文件夹中,我有一个简单的搜索表单,如下所示:

    <% 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>

    <% } %>

这个想法是,当用户提交此表单时,将使用查询文本框的内容,然后根据来 self 的数据库的文章标题进行检查,索引 View 将只显示而不是显示所有文章那些与用户输入的查询相匹配的内容。

当我提交表单时,出现以下错误:

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与一个,或摆脱 .First() .

关于c# - ASP.NET MVC C# 搜索帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4088587/

相关文章:

c# - NotifyPropertyChanged 依赖属性

c# - 如何在 C# 中对属性进行分组?

c# - ViewData 未传递到 ASP.NET Core 2.1 中的布局

asp.net-mvc - 如何在.NET Web应用程序中创建用户身份验证?

asp.net-mvc - Unobtrusive Validation 消息不适用于没有 name 属性的输入

c# - ASP.NET 5 beta 8 中的 Windows 身份验证支持

c# - 是否可以将小数绑定(bind)到 Blazor 中的文本框并删除尾随零?

c# - 如何从一个值中选择两个值

c# - Visual Studio : Tools to rename projects (and directories) automatically

c# - 将 100 KB 的内容发布到 Azure 应用服务 MVC 超时