vb.net 使用 jQuery AJAX 将多个变量发布到 ASP .NET MVC 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17026500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:54:24  来源:igfitidea点击:

Using jQuery AJAX to POST multiple variables to an ASP .NET MVC Controller

c#asp.net-mvcvb.netjquery

提问by Douglas Barbin

I have a controller to which I want to POST 2 items via AJAX: a complex object (my entire viewmodel), and an integer (the id of a particular row). This particular project is in VB .Net, but if someone can answer this in C#, that would be fine (I know both languages fairly well). Either language would work.

我有一个控制器,我想通过 AJAX 向其发布 2 个项目:一个复杂对象(我的整个视图模型)和一个整数(特定行的 id)。这个特定的项目是在 VB .Net 中,但如果有人能用 C# 回答这个问题,那就没问题了(我对这两种语言都很了解)。任何一种语言都可以。

I can POST the viewmodel to the controller without any problem. Once I try to include the integer, the controller can no longer route the request. I know that it is probably an issue of how I am formatting the data that I POST, but I haven't been able to figure out exactly what I need to do.

我可以毫无问题地将视图模型发布到控制器。一旦我尝试包含整数,控制器就无法再路由请求。我知道这可能是我如何格式化我发布的数据的问题,但我一直无法弄清楚我需要做什么。

My controller action looks like:

我的控制器操作如下所示:

<HttpPost>
Public Function UpdateFromDate(viewModel As RetirementBenefitEstimateViewModel, estimateId) As ActionResult
    If viewModel IsNot Nothing AndAlso viewModel.Estimate IsNot Nothing AndAlso viewModel.Estimate.RetirementBenefitsEstimates IsNot Nothing Then

      For Each item In viewModel.Estimate.RetirementBenefitsEstimates.Where(Function(est) est.EstimateId = estimateId)
        ' this is where I update the affected row
        item.UpdateFromDate(viewModel.DateOfBirth, viewModel.EmploymentStartDate, viewModel.PersonId)
      Next item
    End If

    ' Get the previous ViewModel from session
    PerformSessionAction(Of RetirementBenefitEstimateViewModel)(SessionConstants.RetirementEstimate, currentEstimate, SessionAction.GetVar)
    ' update it's .Estimate property
    currentEstimate.Estimate = viewModel.Estimate
    ' save the updated ViewModel to session
    PerformSessionAction(Of RetirementBenefitEstimateViewModel)(SessionConstants.RetirementEstimate, currentEstimate, SessionAction.SetVar)
    ' finished!
    Return New HttpStatusCodeResult(HttpStatusCode.OK)
End Function

The jquery AJAX call in my view looks like:

我视图中的 jquery AJAX 调用如下所示:

$.ajax({
        type: "POST",
        url: '@Url.Action("UpdateFromDate")',
        data: { viewModel : model, estimateId : 3 }
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        cache: false,
        success: function (msg) {
          //alert(JSON.stringify(msg));
          return true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          //alert(errorThrown);
          return false;
        }
      });

How can I POST my viewmodel and the integer (hard-coded to 3 in this example)?

如何发布我的视图模型和整数(在本例中硬编码为 3)?

回答by Douglas Barbin

Scottie's post got me on the right track. I was tempted to mark it as the answer, but it had one tiny problem. The integer would POST correctly, but the viewmodel started showing up as null in the controller. All that was needed to fix this was a simple JSON.parse call.

斯科蒂的帖子让我走上了正轨。我很想将其标记为答案,但它有一个小问题。整数将正确 POST,但视图模型开始在控制器中显示为 null。解决这个问题所需要的只是一个简单的 JSON.parse 调用。

My AJAX call ends up looking like:

我的 AJAX 调用最终看起来像:

var params = {
    viewModel: JSON.parse(model),
    estimateId: 3
};

$.ajax({
    url: '@Url.Action("UpdateFromDate")',
    type: "POST",
    dataType: 'json',
    data: JSON.stringify(params),
    async: false,
    cache: false,
    traditional: true,
    contentType: 'application/json',
    success: function  (msg) {
      //alert(JSON.stringify(msg));
      return true;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      //alert(errorThrown);
      return false;
    }
  });   

回答by Scottie

Try this:

尝试这个:

var params = {
    viewModel: model,
    estimateId: 3
};

$.ajax({
    url: '@Url.Action("UpdateFromDate")',
    type: "POST",
    dataType: 'json',
    data: JSON.stringify(params),
    async: false,
    cache: false,
    traditional: true,
    contentType: 'application/json',
    success: function  (msg) {
      //alert(JSON.stringify(msg));
      return true;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      //alert(errorThrown);
      return false;
    }
  });