以下是场景:
当用户选择Details
按钮(JavaScript函数)时,getPersonId
会按预期获取人员ID。
问题发生的位置:
在选择了personId
之后,我将该Id
发送到ajax
呼叫中。Id
通过了,但遇到了问题:我的成功应该是什么和传递给控制器的personId为空
问题列表:
- 向控制器发送参数时,成功是如何工作的
- C#参数为null
- 调用ajax方法的最佳方式是什么?是否应在单击详细信息按钮时调用此项
Html
<div class="col-md-12">
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@foreach (var viewModel in Model)
{
<tr>
<td>@viewModel.Name</td>
<td>@viewModel.Age</td>
<td><button data-id="@viewModel.PersonId" type="button" data-bind="click: getPersonId" class="btn btn-success" data-toggle="modal" data-target="#details-modal"><span class="fa fa-external-link-square"></span> Details</button></td>
</tr>
}
</tbody>
</table>
</div>
在HTML底部创建PersonViewModel实例
<script>
$(function () {
window.viewModel = new PersonViewModel().init(@Html.Json(Model));
});
</script>
JavaScript
function PersonViewModel() {
var self = this;
self.init = function(data) {
ko.mapping.fromJS(data, {}, self);
ko.applyBindings(self, $("#tblPerson")[0]);
return self;
}
self.getPersonId = function(vm, ev) {
var personId = $(ev.target).data('id');
return personId;
}
self.getPersonEntity = function() {
$.ajax({
type: "POST",
url: '/Person/RetrievePersonEntity',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: ko.toJSON(self.getPersonId),
success: function() {} // not sure what I need here...
});
}
}
C#控制器
[HttpPost]
public JsonResult RetrievePersonEntity(string personId)
{
var result = _personOrchestrator.RetrievePersonEntity(personId);
return Json(result);
}
试试这个:
self.getPersonEntity = function() {
$.ajax({
type: "POST",
url: '/Person/RetrievePersonEntity?personId=' + self.getPersonId(vm, ev),
data: ko.toJSON(self.getPersonId),
success: function() {
return self.getPersonId
}
});
}
你可以试试这个
self.getPersonEntity = function() {
$.ajax({
type: "POST",
url: '/Person/RetrievePersonEntity' ,
data: {personId:self.getPersonId(vm, ev)},
success: function() {
return self.getPersonId
}
});
}