【问题标题】:ASP.NET MVC CORE fails model binding TypeScript Json data through Jquery .ajax()ASP.NET MVC CORE 无法通过 Jquery .ajax() 模型绑定 TypeScript Json 数据
【发布时间】:2020-10-02 17:55:47
【问题描述】:

我的 MVC CORE 控制器方法没有绑定到代码片段 1 中显示的 Ajax 数据。JsonPostBackModel 始终为空。 Ajax 数据是代码片段 2 中所示的序列化 TypeScript Array。MVC 控制器 [HttpPost] 操作具有以下签名。 JsonPostBackModel 如代码片段 3 所示。

[HttpPost]
//[ValidateAntiForgeryToken]
public IActionResult Edit([FromBody] IList<JsonPostBackModel> collection)

Developer Tool Network 选项卡显示 IUserAnswer 的 JSON 数组。有谁知道为什么?

代码片段 1:

    $("#submit").click(function (e) {
      e.preventDefault();
      let formPostBackUrl: string = $("form[id='userAnswersForm']").attr("action");

      if ($("form[id='userAnswersForm']").valid()) {
        let userAnswers: Array<IUserAnswer> = new Array<IUserAnswer>();
        let stringfiedUserData: string = "";

        //formData = serializeTheForm($("form[id='userAnswersForm']"));
        userAnswers = manuallyCreateTheJson();
        if (userAnswers.length > 0) {
          stringfiedUserData = JSON.stringify(userAnswers);
          console.log('stringfiedUserData length', stringfiedUserData.length);
          console.log('stringfiedUserData', stringfiedUserData);

          $.ajax({
            type: "POST",
            url: formPostBackUrl,
            data: stringfiedUserData,
            headers: {
              "CSRF-TOKEN-APP-TOKEN": $('input[name="CSRF-TOKEN-APP-TOKEN"]').val(),
              'Accept': 'application/json',
            },
            contentType: "application/json;charset=utf-8"
          }).done(function (result) {
            console.log('postback result', result.message);
            alert(result.message);
          }).fail(function (error) {
            console.log('postback error', error.message);
            alert(error.message);
          });
        }
      }
    });

  function manuallyCreateTheJson() {
    const userID: string = $('form #userID').val();
    const facilityRelationshipID: string = $('form #facilityRelationshipID').val();
    const facilityID: string = $('form #facilityID').val();
    const fiscalYear: string = $('form #fiscalYear').val();

    const target = $("select, textarea, input:checked, input[type='number'], input[type='text']");

    let userAnswers: Array<IUserAnswer> = new Array<IUserAnswer>();
    target.each(function () {
      let thisTargetElement: any = $(this).get(0);
      let $this: any = $(this);
      console.log('$this', $this);

      const item: IUserAnswer = <IUserAnswer>{};

      item.FacilityID = facilityID
      item.FacilityRelationshipID = facilityRelationshipID;
      item.FiscalYear = fiscalYear;
      item.UserID = userID;
      item.QuestionID = $this.data('questionid');
      item.QuestionKey = $this.data('questionkey');
      item.UserAnswerID = $this.data('useranswerid');

      switch (thisTargetElement.tagName.toLowerCase()) {
        case 'select':
          if ($this.val()) {
            item.AnswerCodeSetID = $this.val();
          }
          break;
        case 'textarea':
          if ($this.text().trim().length !== 0) {
            item.OtherDescription = $this.text();
          }
          break;
        case 'input':
          if ($this.val()) {
            //only non-codeset id would be rendered as number or text input types such Q38 percentages
            if ($this.attr('type') === 'number' || $this.attr('type') === 'text') { 
              item.OtherDescription = $this.val();
            }
            else
              item.AnswerCodeSetID = $this.val();
          }
          break;
      }

      if (item.AnswerCodeSetID || item.OtherDescription ) //has value
        userAnswers.push(item);

    });
    console.log('userAnswers', userAnswers);
    return userAnswers;
  }

代码片段 2

export interface IUserAnswer {

  UserAnswerID: string; /* record primary key */
  FacilityID: string;
  FacilityRelationshipID: string;
  FiscalYear: string;
  QuestionID: string;
  QuestionKey: string;
  AnswerCodeSetID: string;
  UserID: string;
  OtherDescription: string;
}

代码片段 3

  public class JsonPostBackModel
  {
    [JsonPropertyName("UserAnswerID")]
    public string UserAnswerID { get; set; } /* record primary key */

    [JsonPropertyName("FacilityID")]
    public string FacilityID { get; set; }

    [JsonPropertyName("FacilityRelationshipID")]
    public string FacilityRelationshipID { get; set; }

    [JsonPropertyName("FiscalYear")]
    public string FiscalYear { get; set; }

    [JsonPropertyName("QuestionID")]
    public string QuestionID { get; set; }

    [JsonPropertyName("QuestionKey")]
    public string QuestionKey { get; set; }

    [JsonPropertyName("AnswerCodeSetID")]
    public string AnswerCodeSetID { get; set; }

    [JsonPropertyName("UserID")]
    public string UserID { get; set; }

    [JsonPropertyName("OtherDescription")]
    public string OtherDescription { get; set; }
  }

【问题讨论】:

    标签: javascript jquery typescript asp.net-core


    【解决方案1】:

    事实证明,我没有将每个项目属性都转换为字符串,因此 MVC 控制器没想到 Ajax 回发中会混合使用字符串和 int。

    item.FacilityID = facilityID.toString();
    item.FacilityRelationshipID = facilityRelationshipID.toString();
    item.FiscalYear = fiscalYear.toString();
    item.UserID = userID.toString();
    item.QuestionID = $this.data('questionid').toString();
    item.QuestionKey = $this.data('questionkey').toString();
    item.UserAnswerID = $this.data('useranswerid').toString();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      相关资源
      最近更新 更多