[英]How to send data to the ASP.NET Core MVC controller in C#?
I am trying to send data from my Javascript to my post method controller.我正在尝试将数据从我的 Javascript 发送到我的发布方法 controller。 I have knockout as my method to bind from Javascript to my view.
我将淘汰赛作为我从 Javascript 绑定到我的视图的方法。
This is my controller, and this is wher convocationData is null这是我的 controller,这就是 convocationData 是 null
public async Task<ActionResult> CreateConvocation(string convocationData)
{
string baseUrl = "http://localhost:8080";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
This is how I try to call the method using jQuery:这就是我尝试使用 jQuery 调用该方法的方式:
var tmpSession = self.addSession();
var tmpDescription = self.addDesc();
var convocationData = {
sessionCode: tmpSession,
description: tmpDescription
};
$.ajax({
url: '/Convocations/CreateConvocation',
type: 'POST',
dataType: 'json',
data: JSON.stringify(convocationData),
contentType: 'application/json',
success: function (data) {
self.Convocations.push(new Convocation(self.addSession(), self.addDesc()));
self.addDesc("");
self.addSession("");
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Add [FromBody]
attribute like this像这样添加
[FromBody]
属性
[HttpPost]
public async Task<ActionResult> CreateConvocation([FromBody]string convocationData)
{
return text;
}
You can read more here Accepting Raw Request Body Content with ASP.NET Web API您可以在此处阅读更多内容 使用 ASP.NET Web API 接受原始请求正文内容
Also, read zgood's comments to your post.另外,请阅读 zgood 对您的帖子的评论。 Instead of using
JSON.stringify
you should create a corresponding model as he is describing in his comment.而不是使用
JSON.stringify
您应该创建一个相应的 model 正如他在评论中所描述的那样。
JS model class JS model class
class Convocation {
constructor(sessionCode, description) {
this.sessionCode = sessionCode;
this.description = description;
}
}
C# DTO class C# DTO class
public class Convocation
{
public string SessionCode{ get; set; }
public string Description { get; set; }
}
Then you can update your action method to this然后您可以将您的操作方法更新为此
[HttpPost]
public async Task<ActionResult> CreateConvocation([FromBody]Convocation convocation)
{
return text;
}
and ajax post to this:和 ajax 发布到此:
$.ajax({
url: '/Convocations/CreateConvocation',
type: 'POST',
dataType: 'json',
data: new Convocation(tmpSession, tmpDescription),
contentType: 'application/json',
success: function(data) {
self.Convocations.push(new Convocation(self.addSession(), self.addDesc()));
self.addDesc("");
self.addSession("");
},
error: function(err) {
alert(err.status + " : " + err.statusText);
}
});
I didn't test the code but it should work.我没有测试代码,但它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.