[英]Null Value while passing json data to mvc 6 web application using knockout.js
使用knockout js我试图将json数据传递给mvc 6控制器动作。 我只能看到dto参数的空值。 如果我在mvc 5中使用相同的方法,则将值赋给dtos。 我在代码中遗漏了什么。
var LoginAuthentication = {
username: ko.observable(),
password: ko.observable(),
GetLoginAuthentication: function () {
if ($("#loginAuthentication").valid()) {
var self = this;
var ajaxUrl = ApplicationRootUrl("LoginAuthentication", "Home");
var UserCrendential = {
UserName: self.username(),
Password: self.password()
};
console.log(ko.toJSON(UserCrendential));
$.ajax({
type: "POST",
url: ajaxUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: ko.toJSON(UserCrendential),
success: function (data) {
},
error: function (err) {
}
});
}
}
};
这是dto类
public class LoginAuthenticationModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
以下是控制器方法。
public void LoginAuthentication(LoginAuthenticationModel loginAuthenticationModel)
{
if (ModelState.IsValid)
{
try
{
}
catch (Exception exception)
{
}
}
}
在控制器中包含[FromBody]
以从请求正文中读取json数据
public void LoginAuthentication([FromBody]LoginAuthenticationModel loginAuthenticationModel)
{
if (ModelState.IsValid)
{
}
}
下面的行解决了问题,但我不知道这是一个正确的解决方案。 我从ajax调用dataType中删除下面的代码:“json”
并将数据更改为loginAuthenticationModel而不转换为任何内容
var LoginAuthentication = {
username: ko.observable(),
password: ko.observable(),
GetLoginAuthentication: function () {
if ($("#loginAuthentication").valid()) {
var self = this;
var ajaxUrl = ApplicationRootUrl("LoginAuthentication", "Home");
var loginAuthenticationModel = {
UserName: self.username(),
Password: self.password()
};
$.ajax({
type: "POST",
url: ajaxUrl,
dataType: "json",
data: loginAuthenticationModel,
success: function (data) {
},
error: function (err) {
}
});
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.