使用部分视图发送带有数据的Json

时间:2018-06-01 05:23:46

标签: c# json ajax partial-views

我在控制器中有一个动作的以下chtml代码。数据由ajax发送到操作。 chtml部分:

<li>
    <button id="abandon-popup" onclick="Transfer(@Model.Id)">
       Transfer <i class="icon-arrow-right"></i>
    </button>
</li>

功能转移:

function Transfer(modelId) {
    //alert(modelId);
    $.ajax({

        type: "GET",
        url: "/Internet/Transfer",
        data: "id=" + modelId,
        success: function (responsedata) {
            alert("ok");
            window.location.href = responsedata.newUrl;
        },
        error: function (data) {
          console.log("KO");
        }
    })
}

控制器中的操作:

public ActionResult Transfer(long id)
{
  *some actions*
  return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
}

但是我收到了500内部错误:

  

此请求已被阻止,因为在GET请求中使用此信息时,可能会向第三方网站披露敏感信息。要允许GET请求,请将JsonRequestBehavior设置为AllowGet

知道如何纠正这个问题吗?

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });

进入

return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) }, JsonRequestBehavior.AllowGet);

按以下方式将GET方法更改为POST方法:

客户方:

function Transfer(modelId) {
//alert(modelId);
$.ajax({

    type: "POST",
    url: "/Internet/Transfer",
    data: {id: modelId},
    success: function (responsedata) {
        alert("ok");
        window.location.href = responsedata.newUrl;
    },
    error: function (data) {
      console.log("KO");
    }
})
}

控制器端:

[HttpPost]
public ActionResult Transfer(long id)
{
  *some actions*
  return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
}

答案 1 :(得分:0)

使用此

  return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml",
                             commonModel
                 )}, JsonRequestBehavior.AllowGet);
  

默认情况下,ASP.NET MVC框架不允许您使用JSON有效内容响应HTTP GET请求。如果需要发送JSON以响应GET,则需要使用JsonRequestBehavior.AllowGet作为Json方法的第二个参数来显式允许该行为。但是,恶意用户有可能通过称为JSON Hijacking的进程获得对JSON有效负载的访问权限。您不希望在GET请求中使用JSON返回敏感信息。