我有以下控制器:
public JsonResult EquipmentSelect(string term)
{
var equipmentSearchViewModel = new EquipmentSearchViewModel
{
EquipmentList = iEquipmentRepository.FindBy(t => t.equipment_name.Contains(term)
|| t.equipment_id.Contains(term)),
};
var filteredEquipment = equipmentSearchViewModel.EquipmentList.ToList();
var sortableData = filteredEquipment.AsQueryable();
var jsonData = new
{
rows = (
from m in filteredEquipment
select new
{
equipment_id = m.equipment_id,
equipment_name = m.equipment_name
}
).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
和下面的js文件:
$(function () {
$('#search').click(function () {
var searchText = $('#txtsearch').val();
getEquipment(searchText);
})
})
// View model declaration
var EquipmentViewModel = {
Profiles: ko.observableArray([])
};
// Bind the equipment
bindData = function (equipment) {
var EquipmentViewModel = {
Profiles: ko.observableArray([])
};
EquipmentViewModel.Profiles(equipment);
ko.applyBindings(EquipmentViewModel);
}
getEquipment = function (searchTerm) {
var url = 'EquipmentSelect/Equipment';
$.ajax({
url: url,
cache: false,
contentType: 'application/json',
data: '{"term": "' + searchTerm + '"}',
type: "POST",
success: function (result) {
bindData(result.rows);
},
error: function (jqXHR) {
$('#message').html(jqXHR.statusText);
}
});
}
最后是我的观点:
@{
ViewBag.Title = "KnockoutExample";
}
<script src="~/Scripts/knockout-2.2.1.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/Scripts/koViewModel.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<h2>Knockout Example</h2>
<div>
<fieldset>
<legend>Search</legend>
<span>Search For</span>
<input type="text" name="txtsearch" id="txtsearch" />
<input type="button" value="Submit" id="search"/>
</fieldset>
</div>
<table id="myTable" class="table table-striped table-bordered table-condensed">
<tr>
<th>Equipment ID</th>
<th>Equipment Name</th>
</tr>
<tbody data-bind="foreach: Profiles">
<tr">
<td data-bind="text: equipment_id"></td>
<td data-bind="text: equipment_name"></td>
</tr>
</tbody>
</table>
<p id="message"></p>
当我单击搜索按钮时,我会得到我想要的结果。如果我再次单击它,我会得到相同的数据,但每个原始计数都会重复。例如,如果第一次调用返回 20 个项目,则第二次单击返回 20 个项目,每一个都返回 20 个。我需要以某种方式清除我的视图模型并在每次单击搜索按钮时重新填充。