gpt4 book ai didi

javascript - Ajax不会调用MVC Controller 方法

转载 作者:太空宇宙 更新时间:2023-11-04 15:45:00 26 4
gpt4 key购买 nike

我的 javascript 中有一个 AJAX 函数来调用我的 Controller 方法。当我运行 AJAX 函数(单击按钮时)时,它不会遇到方法中的断点。这一切都运行成功:和错误:。我需要更改什么才能使其实际将值从 $CSV.text 发送到我的 Controller 方法?

JAVASCRIPT:

// Convert JSON to CSV & Display CSV
$CSV.text(ConvertToCSV(JSON.stringify(data)));

$.ajax({
url: '@Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value : $CSV.text() },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});

Controller :

[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText = "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var obj = new
{
success = false,
responseText = "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
}

结果

enter image description here

enter image description here

enter image description here

最佳答案

您应该更改您发布到 Controller 的数据以及您发布到的Action:

data: { value = $CSV.text() }

url: '@Url.Action("EditFence", "Configuration")'

$CSV 可能是与 html 元素相关的 jquery 对象。您需要读取它的文本属性并将其作为数据而不是 jQuery 对象传递。

执行上述更改即可做出正确的 POST。但是,还有另一个关于您的 Controller 的问题。您的 Controller 在完成工作后不会响应 AJAX 调用,而是发出重定向。

更新

it would be helpful for you to tell me how the ActionResult should look, in terms of a return that doesn't leave the current view but rather just passes back that it was successful.

您发布的操作应如下所示进行重构。正如您所看到的,我们使用 try/catch 来捕获任何异常。如果没有抛出任何异常,我们假设一切正常。不然的话,就出事了。在好的情况下,我们返回带有成功消息的响应,而在坏的情况下,我们返回带有失败消息的响应。

[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText= "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
catch(Exception ex)
{
// log the Exception...

var obj = new
{
success = false,
responseText= "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
}

进行此重构后,您可以在客户端中使用它,如下所示:

$CSV.text(ConvertToCSV(JSON.stringify(data)));

$.ajax({
url: '@Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value = JSON.stringify($CSV.text()) },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});

关于javascript - Ajax不会调用MVC Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43615245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com