Ajax调用后控制器中的参数为空

时间:2016-04-12 17:33:10

标签: javascript c# jquery ajax

以下是该方案:

当用户选择Details按钮时,JavaScript函数getPersonId会按预期抓取personId。

问题出在哪里:

选择personId后,我将Id发送到ajax来电。 Id获得通过,但遇到问题:我的成功应该是什么?传递给控制器​​的personIn为空

  

问题列表:

     
      
  1. 将参数发送到控制器时,Success如何工作?
  2.   
  3. C#参数为空。
  4.   
  5. 调用ajax方法的最佳方法是什么?是否应该在详情按钮上调用?
  6.   

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#Controller

[HttpPost]
public JsonResult RetrievePersonEntity(string personId)
{
    var result = _personOrchestrator.RetrievePersonEntity(personId);

    return Json(result);
}

2 个答案:

答案 0 :(得分:2)

试试这个:

 self.getPersonEntity = function() {
        $.ajax({
            type: "POST",
            url: '/Person/RetrievePersonEntity?personId=' + self.getPersonId(vm, ev),
            data: ko.toJSON(self.getPersonId),
            success: function() {
                return self.getPersonId
            }  
        });
    }

答案 1 :(得分:0)

你可以尝试这样

self.getPersonEntity = function() {
    $.ajax({
        type: "POST",
        url: '/Person/RetrievePersonEntity' ,
        data: {personId:self.getPersonId(vm, ev)},
        success: function() {
            return self.getPersonId
        }  
    });
}