我正在尝试在我的项目中创建按关键字操作搜索。 下面是视图中的代码:
<form method="get">
<input type="radio" name="news" value="newest"> Newest First
<input type="radio" name="news" value="keyword"> Keyword Search
<input type="search" name="keyword" id="search" />
<button type="submit" value="Search"><span class="glyphicon glyphicon-search"></span></button>
这是模型:
public class News
{
public int Id { get; set; }
public string Date { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public string Link { get; set; }
}
这是控制器不工作的地方。最新的优先提供正确的数据,但关键字优先只是提供列表中的每个对象。
[HttpGet]
public ActionResult News(String news = null, String text = null)
{
if (news == "newest")
{
var model =
from n in _news
orderby n.Date
select n;
return View(model);
}
else {
var model =
from n in _news
.Where(n=> text == null || n.Name.Contains(text))
select n;
return View(model);
}
}
以下是新闻列表的一些元素:
static List<News> _news = new List<News>
{
new News {
Id = 1,
Date = "01/01/2017",
Name = "blabla",
Description = "blabla",
Image = "blabla.jpg",
Link = "dassda"
},
new News {
Id = 2,
Date = "vlava",
Name = "dada",
Description = "dsadasa",
Image = "dasdsa.jpg",
Link = "sdaa"
};
您的"搜索"输入具有与参数名称不匹配的name="keyword"
。更改一个或另一个,以便它们匹配。
在视图中
<input type="search" name="keyword" id="search" />
或在控制器中
public ActionResult News(string news, string keyword)
请注意,无需添加= null
(默认情况下它们已经是)
但是,您应该做的是创建一个包含搜索属性和集合的视图模型
public class MyViewModel
{
public string News { get; set; } // an enum would be a better choice
public string Keyword { get; set; }
public IEnumerable<News> NewsList { get; set; }
}
并使用视图中的HtmlHelper
方法强绑定到模型,例如
@Html.TextBoxFor(m => m.KeyWord, new { type="search" })
以便在返回视图时保留输入中的值。