-3

Everything works as expected until the json string is deserialized after the post back.

Class:

public class RegretLetterDetail
{
    public int PositionID { get; set; }
    [Display(Name = "Description of Position")]
    public string PositionReference { get; set; }
    public string PositionName { get; set; }
    public int PayrollNumber { get; set; }
    [Display(Name = "Name of Candidate")]
    public string PersonName { get; set; }
    public bool PersonSelected { get; set; }
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [Display(Name = "Send")]
    public DateTime DateSend { get; set; }
    public bool IsDeleted { get; set; }
    public bool Undelete { get; set; }
    [Display(Name = "Changed By")]
    public string ChangedBy { get; set; }
    public bool SendEmial { get; set; }
    public bool SendSMS { get; set; }

}

jQuery Serialization:

$.fn.serializeObject = function () {
  var o = {};
  var a = this.serializeArray();
  $.each(a, function () {
    if (o[this.name] !== undefined) {
      if (!o[this.name].push) {
        o[this.name] = [o[this.name]];
      }
      o[this.name].push(this.value || '');
    } else {
      o[this.name] = this.value || '';
    }
  });
  return o;
};

Ajax Postback:

var DetailParam = "@Html.Raw(Url.Action("_RegretPersonSelect", "Home"))";
var DetailData = JSON.stringify($('#_PersondetailRegret').serializeObject());
$.ajax({
  type: 'POST',
  url: DetailParam,
  data: DetailData,
  success: function (result) {
    $("#RegretLetterto").html(result);
  }
});

JsonString:

"{\"__RequestVerificationToken\":\"ZQn4bLDapqavi7dagatgluRffgxJGSJYHlRdMOXyzHN_LLPKrDZjdDUTVwYiLaOd8oTnt1Tqzw0deLLADlZbtvGZdIhUIPPRBzmQx_grHnBCnk15qfHMN3rds9Xy7eQs0\",
\"[0].PersonSelected\":[\"true\",\"false\"],\"[0].PayrollNumber\":\"100001\",\"[0].SendSMS\":[\"true\",\"false\"],
\"[1].PersonSelected\":[\"true\",\"false\"],\"[1].PayrollNumber\":\"100002\",\"[1].SendSMS\":[\"true\",\"false\"],
\"[2].PersonSelected\":[\"true\",\"false\"],\"[2].PayrollNumber\":\"100003\",\"[2].SendSMS\":[\"true\",\"false\"],
\"[3].PersonSelected\":[\"true\",\"false\"],\"[3].PayrollNumber\":\"100005\",\"[3].SendSMS\":[\"true\",\"false\"],
\"[4].PersonSelected\":[\"true\",\"false\"],\"[4].PayrollNumber\":\"100006\",\"[4].SendSMS\":[\"true\",\"false\"]
}"

Deserialization Code:

System.Web.Script.Serialization.JavaScriptSerializer serializer =
    new System.Web.Script.Serialization.JavaScriptSerializer();
model = (List<RegretLetterDetail>)serializer.Deserialize(
    jsonString, typeof(List<RegretLetterDetail>));

The deserialize object returned is always empty. How / What do I need to do to make sure that the list of values is successfully desterilized. What potentially obvious thing am I missing?

4
  • Put an example of the serialized JSON sent by JS. Commented Oct 23 at 8:43
  • It is already displayed under the heading JsonString Commented Oct 23 at 8:52
  • U have __RequestVerificationToken in JSON. How would know the deserializer what to do with it? Fields like "PersonSelected":["true","false"] are ambiguous they are a list values for a single boolean property. This JSON looks like a form post (like application/x-www-form-urlencoded) rather than a clean JSON object or array. Commented Oct 23 at 9:06
  • based on previous usage, it only maps the matching fiedls and ignores the rest. I just not sure about the [X].PropertyName format the jsonstring is returning. the true false is also not currently a problem as it only take the first one (previous implementation). Commented Oct 23 at 9:10

1 Answer 1

1

Just send the serialized form data to the action method. As long as the method's parameter name and the JSON data root match, the framework will do the rest:

AJAX post:

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$('#btnSubmitRegret').click(function () {
    var url = "@Url.Action("_RegretPersonSelect", "Home")";
    var model = $('#_PersondetailRegret').serializeObject();

    $.ajax({
        type: 'POST',
        url: url,
        data: { model },                
        dataType: "json",
        success: function (result) {
            $("#RegretLetterto").html(result);
        },
    });
});

Action:

[HttpPost]
public async Task<IActionResult> _RegretPersonSelect(RegretLetterDetail model)
{
    // model is an object populated with the posted values
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.