Obs*_*vus 10 c# asp.net asp.net-mvc search actionresult
我首先使用ASP.NET MVC 4和实体框架模型.
在我的"Masterpage.cshtml"中,我想要一个包含文本框和按钮的局部视图.
搜索正在查找项目标题,如果文本包含项目标题,则应显示这些项目.
提交文本时,@renderbody()
应显示包含项目的视图.
我的问题是如何以一种好的方式做到这一点?什么是一个好的和简单的方法?
到目前为止,我已经这样做了:
在我的存储库中创建了一个执行搜索功能的方法:
public List<News> Search(string query)
{
var queryz = db.News.Where(x => x.Title.Contains(query));
return queryz.ToList();
}
Run Code Online (Sandbox Code Playgroud)
现在谈到我的Searchcontroller我有点失去了如何做到这一点.因为一个actionresult需要是具有字符串查询参数的partialview,而另一个包含将显示项目的视图?
我现在所做的是将整个过程放在同一个动作中:
Repository rep = new Repository();
[HttpPost]
public ActionResult Search(string query)
{
var searchlist = rep.Search(query);
var model = new ItemViewModel()
{
NewsList = new List<NewsViewModel>()
};
foreach (var NewsItems in searchlist)
{
FillProductToModel(model, NewsItems);
}
return View(model);
}
private void FillProductToModel(ItemViewModel model, News news)
{
var productViewModel = new NewsViewModel
{
Description = news.Description,
NewsId = news.Id,
Title = news.Title,
link = news.Link,
Imageurl = news.Image,
PubDate = news.Date,
};
model.NewsList.Add(productViewModel);
}
Run Code Online (Sandbox Code Playgroud)
任何形式的帮助都很受欢迎!
Mat*_*ull 24
您可以使用以下方法:
Index.cshtml
有一个DIV调用搜索控制器动作,另一个DIV显示结果.
<div id="search-form">
@Html.Action("Search", "Home"); // GET action in controller that displays form
</div>
<div id="search-results">
</div>
Run Code Online (Sandbox Code Playgroud)
_SearchFormPartial.cshtml
创建一个包含搜索表单的部分视图.您可以Ajax.BeginForm
在用户搜索结果时使用,结果将由search-results
AJAX 显示在Index.cshtml 的DIV中.UpdateTargetId
指定我们要将搜索结果传递给search-results
DIV.
@using (Ajax.BeginForm("Search", "Home", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "search-results"
}))
{
<div>
@Html.TextBox("query")
<input type="submit" value="Search" />
</div>
}
Run Code Online (Sandbox Code Playgroud)
在您的控制器中,您需要一个操作来显示表单(上面的部分视图),另一个操作来处理搜索查询并重新调整另一个显示结果的局部视图:
[HttpGet]
public ActionResult Search()
{
return PartialView("_SearchFormPartial");
}
[HttpPost]
public ActionResult Search(string query)
{
if(query != null)
{
try
{
var searchlist = rep.Search(query);
var model = new ItemViewModel()
{
NewsList = new List<NewsViewModel>()
};
return PartialView("_SearchResultsPartial", model);
}
catch (Exception e)
{
// handle exception
}
}
return PartialView("Error");
}
Run Code Online (Sandbox Code Playgroud)
_SearchResultsPartial.cshtml
这部分将显示结果.这是强烈打字的ItemViewModel
.
@model Namespace.ViewModels.ItemViewModel
@if (Model.SearchResults.Count == 0)
{
<h3 class="text-error">No items matched your search query!</h3>
}
else
{
foreach (var result in Model.NewsList)
{
// display search results
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27456 次 |
最近记录: |