I have tried to post json data from AngularJs WARNING: No mapping found for HTTP request with URI [/springMvcApp/loginTry] in DispatcherServlet with name 'dispatcher'
post to an ASP.NET MVC controller. Here is the json data example :
https://www.python.org/ftp/python/2.7.15/python-2.7.15.msi
AngularJs code:
$http
Controller:
var postdata = {
Email: "test1@mail.com",
selectedanswer: {0: 3, 1: 2, 2: 0, 3: 3, 4: 1}
};
My model:
$http({
url: "/page/PostFileWithData",
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
method: "POST",
dataType: "json",
traditional: true,
data: JSON.stringify(postdata)
}).success(function (data) {
console.log(data);
}).error(function (data) {
console.log('fail');
});
Now the problem is that I am getting public JsonResult PostFileWithData(UserModel userdata)
{
UserModel udata = new UserModel {
Email = userdata.Email
selectedanswer = userdata.selectedanswer
};
return Json(udata, JsonRequestBehavior.AllowGet);
}
field ok in console.log but public class UserModel {
public string Email { get; set; }
public string selectedanswer { get; set; }
}
is email
Like this
selectedanswer
答案 0 :(得分:2)
由于您从Ajax传递Key-Value对象,因此请将模型更改为
public class UserModel
{
public string Email { get; set; }
public Dictionary<int,int> selectedanswer { get; set; }
}
或者,也可以在字符串中发送selectedanswer
,如下所示:
var postdata = {
Email: "test1@mail.com",
selectedanswer: "{0: 3, 1: 2, 2: 0, 3: 3, 4: 1}"
};
希望这有帮助。
答案 1 :(得分:0)
模型绑定不适用于selectedanswer
属性,因为它被声明为string
类型,并且您没有从客户端代码发送字符串值。如果发送字符串值
var postdata = {
Email: "test1@mail.com",
selectedanswer: "{ 0: 3, 1: 2, 2: 0, 3: 3, 4: 1 }"
};
虽然这可能会解决您的模型绑定问题,但这不是解决问题的干净方法。现在在您的action方法中,您需要解析此字符串并从中提取项目。 还有另一种干净的方法。
您希望发送一份答案列表及其问题ID /索引。创建一个表示结构化的视图模型,并在UserModel类中使用它的集合。
public class UserModel
{
public string Email { get; set; }
public List<Answer> SelectedAnswers { set; get; }
}
public class Answer
{
public int QuestionId { set; get; }
public int AnswerId { set; get; }
}
现在发送一个项目数组,每个项目都包含QuestionId
和AnswerId
属性值。
var postdata = { Email: "test1@mail.com",
SelectedAnswers : [
{ QuestionId:0, AnswerId:3 },
{ QuestionId:1, AnswerId:2 },
{ QuestionId:2, AnswerId:0 },
{ QuestionId:3, AnswerId:3 },
{ QuestionId: 4, AnswerId:1}
] };
// to do : send postdata