查看
@section Scripts{
<script>
$(function () {
$('#UserSearch').click(function () {
$.ajax({
url: this.href,
cache:false,
type: 'POST',
data: {id:$('#SearchName').val()},
success: function (result) {
$('#ajaxsample').html(result);
}
});
return false;
});
});
</script>
}
<table>
<tr>
<td>
<input type="text" id="SearchName"/>
</td>
<td>
<a id="UserSearch" href='@Url.Action("Contribute", "Project")'>Search</a>
</td>
</tr>
</table>
<div id="ajaxsample">
T_T
</div>
控制器
[HttpPost]
public ActionResult Contribute(String id)
{
String UserName = id;
PMSDBContext PMP = new PMSDBContext();
List<_ContributeViewModel> result = new List<_ContributeViewModel>();
result = PMP.Users
.Join(PMP.Friendships, u => u.UserID,
f => f.FriendID,
(u, f) => new { u, f })
.Where(m => m.f.UserID == 1 && m.u.Name.Contains(UserName) && m.f.Status == 1)
.Select(s => new _ContributeViewModel
{
UserID = s.u.UserID,
PhoneNo=s.u.PhoneNo,
Facebook=s.u.Facebook,
Name=s.u.Name
}
).ToList();
return View("UserSearch",result);
}
用户搜索视图
@model List<PMS.View_Model._ContributeViewModel>
@{
ViewBag.Title = "SearchResult";
}
<table>
<tr>
<th>
<u>Search Result</u>
</th>
</tr>
<tr>
<th>Name</th>
<th>PhoneNo</th>
<th>FaceBook</th>
</tr>
@foreach (var item in Model.Where(model => model.UserID != null))
{
<tr>
<td>
@Html.DisplayFor(model => item.Name)
</td>
<td>
@Html.DisplayFor(model => item.PhoneNo)
</td>
<td>
@Html.DisplayFor(model => item.Facebook)
</td>
</tr>
}
</table>
当我第一次单击“{1}}中的某些文字的搜索按钮时,textbox
将UserSearch View
替换为数据库结果,但第二次重新加载页面,"T_T"
替换UserSearch View,第三次用户搜索视图会再次替换"T_T"
并且会不断发生...问题是我可以"T_T"
在每次点击中替换UserSearch View
吗?
答案 0 :(得分:0)
您可以使用tagbuilder构建html标记并发送
,而不是返回完整视图[HttpPost]
public MvcHtmlString Contribute(String id)
{
String UserName = id;
PMSDBContext PMP = new PMSDBContext();
List<_ContributeViewModel> result = new List<_ContributeViewModel>();
result = PMP.Users
.Join(PMP.Friendships, u => u.UserID,
f => f.FriendID,
(u, f) => new { u, f })
.Where(m => m.f.UserID == 1 && m.u.Name.Contains(UserName) && m.f.Status == 1)
.Select(s => new _ContributeViewModel
{
UserID = s.u.UserID,
PhoneNo=s.u.PhoneNo,
Facebook=s.u.Facebook,
Name=s.u.Name
}
).ToList();
StringBuilder output = new StringBuilder();
TagBuilder ulTag = new TagBuilder("ul");
foreach (var item in result )
{
output.Append(ulTag.ToString());
ulTag = new TagBuilder("ul");
}
output.Append(ulTag.ToString();
return output.ToString();
}
我认为您面临的问题是由于整个页面被渲染以及在div中替换它的问题。
答案 1 :(得分:0)
尝试以下代码
$('#UserSearch').click(function () {
$.ajax({
url: '/Project/Contribute',
dataType:'html',
type: 'POST',
data: { id:$('#SearchName').val() },
success: function (result) {
$('#ajaxsample').html(result);
}
});
return false;
});
你的行动将是
[HttpPost]
public PartialViewResult Contribute(String id)
{
//Your logic. .....
return PartialView("UserSearch",result);
}
通常它会起作用......