我需要在返回的搜索结果中突出显示搜索字词吗? 我搜索了很多并阅读了很多文章,但所有文章都与我的结构非常不同
这是我的控制器
public ActionResult Help(string searchString)
{
var repsearch = new RepositorySearch();
List<Question> question = new List<Question>();
if (!string.IsNullOrEmpty(searchString))
{
question = repsearch.GetAllQuestion().Where(n => n.Qu.Contains(searchString)).ToList();
}
return Request.IsAjaxRequest() ? (ActionResult)PartialView("_QuestionPartial", question) : View(question);
}
这是我的ajax
$('#FormSearch').submit(function (event) {
event.preventDefault();
var url = '/Home/Help?' + searchString;
$.ajax({
url: url,
type: 'POST',
cache: false,
data: { searchString: $('#search').val(); },
success: function (result) {
window.history.replaceState("#intagsname", "Title", url);
$('#intagsname').html(result);
}
});
});
这是_QuestionPartial
@using iranhoidaytour_com.Models
@if (Model.Count > 0)
{
<ul>
@foreach (Question q in Model)
{
<li>
<h5>@q.Qu</h5>
<p>@q.Ans</p>
</li>
}
</ul>
}
如何在返回的搜索结果中突出显示搜索字词?
这是我的主视图的html
<div class="row" id="searchhelp">
<div class="container">
@using (Html.BeginForm("Help", "Home", FormMethod.Get, new { @id = "FormSearch", @class = "form-group container" }))
{
@Html.TextBox("search", null, new { @class = "form-control col-md-10", @placeholder = "What Is Your Question?Enter Keyword!" })
<button type="submit" class="left " id="btn-search">
<i class="fa fa-search" aria-hidden="true"></i>
</button>
}
</div>
</div>
<div id="helpicons" class="container">
<div id="tagsname">
<div id="intagsname">
@Html.Partial("_QuestionPartial", Model)
</div>
</div>
</div>
答案 0 :(得分:1)
您可以使用javascript将搜索文本的任何实例包装在具有类名
的元素中var container = $('#intagsname');
$('#FormSearch').submit(function (event) {
event.preventDefault();
var searchString = $('#search').val(); // get the search string
var replacement = '<span class="highlight">' + searchString + '</span>'; // define replacement text
$.ajax({
url: '@Url.Action("Help", "Home")', // don't hard code you url's
type: 'POST',
cache: false,
data: { searchString: searchString },
success: function (result) {
window.history.replaceState("#intagsname", "Title", url);
$('#intagsname').html(result);
var questions = container.find('h5'); // get all question text
$.each(questions, function() {
var text = $(this).html(); // get the text
text = text.replace(new RegExp(searchString, 'g'), replacement); // replace it
$(this).html(text); // update it
});
}
});
});
然后创建一个样式以突出显示搜索文本,例如
.highlight {
font-weight: bold;
color: red;
}
或者,您可以使用正则表达式修改文本以在控制器中包含html标记,然后在视图中使用@Html.Raw()
来显示它。