我在使用 ASP.Net 时遇到了问题,导致我的头发掉光了。我可以使用不同的方法来绑定模型的某些部分,但没有一种方法可以绑定所有数据。
控制器动作签名
// Post: Profile/{customerId}/SetKnockOutQuestions/{profileId}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SetKnockOutQuestions(Int32 customerId,
Int32 profileId,
Int32 parentProfileId,
IEnumerable<ProfileKnockOutQuestionModel> questions)
{
ProfileKnockOutQuestionModel 类的相关数据成员
public sealed class ProfileKnockOutQuestionModel {
/// <summary>
/// Parameterless constructor is required for auto-passing GET/POST data to controller actions.
/// </summary>
public ProfileKnockOutQuestionModel() { }
[Required]
[DisplayName("Lead Type Id")]
public Int32 AdminLeadType { get; set; }
//[Required]
//[DisplayName("Question Type")]
[UIHint("GridForeignKey")]
public Int16 QuestionTypeId { get; set; }
[Required]
[DisplayName("Question Text")]
public String QuestionText { get; set; }
[Required]
[DisplayName("Pass Answer")]
public String Answer1Text { get; set; }
[Required]
[DisplayName("Fail Answer")]
public String Answer2Text { get; set; }
[Required]
[DisplayName("Price")]
[DataType(DataType.Currency)]
[Range(0, Int16.MaxValue)]
public Decimal Price { get; set; }
public Int32 ProfileKnockOutQuestionId { get; private set; }
public Int32 ProfileId { get; private set; }
public Int32 ParentProfileId { get; private set; }
public Int32 CustomerId { get; private set; }
public Int32 AdminKnockOutQuestionId { get; private set; }
尝试以 JSON 编码的 javascript 代码发送数据
$.ajax({
url: "/mvc/Profiles/78219/SetKnockOutQuestions/1605111",
data: JSON.stringify({ questions: data,
parentProfileId : 1605105
}),
type: "POST",
contentType: "application/json; charset=utf-8"
});
发送此数据(为简洁起见)
{
"questions":[
{
"AdminKnockOutQuestionId":8,
"AdminLeadType":4,
"Answer1Text":"Ya really!",
"Answer2Text":"no wai",
"CustomerId":78219,
"ParentProfileId":1605105,
"Price":2,
"ProfileId":1605111,
"ProfileKnockOutQuestionId":0,
"QuestionText":"Really? Auto",
"QuestionTypeId":0
},
但是一旦我们开始行动,模型绑定器只绑定了字符串、价格和 AdminLeadType。其余数据全为零。在注意到所有正确解析的字段都具有它们并且没有任何改变之后,我尝试将[Required]
and属性添加到其余的数字字段。[DisplayName("")]
我尝试发送的另一种方式是作为常规形式的编码帖子。
AXAJ javscript
$.ajax({
url: "/mvc/Profiles/78219/SetKnockOutQuestions/1605111",
data: { questions: data,
parentProfileId : 1605105
},
type: "POST",
});
这会导致如下的帖子正文(从 Chrome 的网络检查器复制/粘贴;我可以发布未解析的 url 编码版本,但请相信我,与号等都是按顺序排列的):
questions[0][AdminKnockOutQuestionId] = 8
questions[0][AdminLeadType] = 4
questions[0][Answer1Text] = Ya really!
questions[0][Answer2Text] = no wai
questions[0][CustomerId] = 78219
questions[0][ParentProfileId] = 1605105
questions[0][Price] = 2
questions[0][ProfileId] = 1605111
questions[0][ProfileKnockOutQuestionId] = 0
questions[0][QuestionText] = Really? Auto
questions[0][QuestionTypeId] = 0
这有相反的问题。根本没有任何约束,因为模型状态吓坏了,说所有字符串值都丢失了,即使我可以在 Request 对象的 VS 调试器视图中清楚地看到它们。
我的模型绑定到底做错了什么?