[英]Making an AJAX request to an MVC controller and getting the data from the response in js
On button click I am trying to send a product name value that the user enters into a textbox to the server to be modified and then back to the page using AJAX. 在按钮上单击,我正在尝试将用户输入到文本框中的产品名称值发送到要修改的服务器,然后使用AJAX返回到页面。 I am getting into the ChangeName method in the controller but not getting into my success function to alert the new name. 我正在进入控制器中的ChangeName方法,但没有进入成功函数来提醒新名称。
The JS: JS:
$("#changeNameButton").click(function () {
var productName = $("#Name").val();
$.ajax({
url: '/Products/ChangeName/',
type: 'POST',
dataType: 'JSON',
data: {name: productName},
success: successFunc
});
});
function successFunc(data) {
alert(data);
}
The controller: 控制器:
public string ChangeName(string name)
{
string changedName = ChangeNameHelper(name);
return changedName;
}
If anyone can give recommendations on the proper way to make asynchronous calls to a controller in MVC5/6 this would be great. 如果任何人都可以提出有关在MVC5 / 6中对控制器进行异步调用的正确方法的建议,那将很棒。
My main problem is that I am never getting into the successFunc() on response. 我的主要问题是,我永远不会在响应时进入successFunc()。
Regarding your comment, if you return just a string MVC will convert that to json. 关于您的评论,如果您仅返回一个字符串,MVC会将其转换为json。
Now, in your updated code you still call a method inside itself. 现在,在更新的代码中,您仍然可以在其内部调用方法。 Please call string changedName = ChangeNameForResult(name);
请调用string changedName = ChangeNameForResult(name);
or any function with another name. 或其他名称的函数。
Install Newtonsoft.Json via nuget package manager and in your controller do this 通过nuget软件包管理器安装Newtonsoft.Json并在您的控制器中执行此操作
Public ActionResult ChangeName(string name)
{
// get your object you want to serialize let's say res
return JsonConvert.SerializeObject(res);
}
I needed to set dataType: 'text' rather than JSON since I am returning a simple string. 我需要设置dataType:'text'而不是JSON,因为我要返回一个简单的字符串。
dataType is the type of data being returned and contentType is the type of data being sent. dataType是要返回的数据类型,contentType是要发送的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.