I have a model having a field as Dictionary type need to post to back end controller action. I am wondering how should I define the model object in JQuery?
I keep getting primitive error from ajax call with the following code:
var templateBuilder = {
TemplateTitle: "Title",
ParagraphTitle: "",
ParagraphTitleList: "",
ParagraphText: "",
ParagraphId: "",
ParagraphOrder: "",
ParagraphDictionary: ""
};
templateBuilder.ParagraphDictionary = dict; //dict is a Dictionary<int, int> type variable I populated earlier.
$.ajax({
url: "/TemplateBuilder/Build",
type: "POST",
data: templateBuilder,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("successful");
},
error: function(response) {
alert("fail");
alert(response.responseText);
}
});
At the backend action method I have:
public ActionResult Build([FromUri]TemplateBuilderViewModel templateBuilder)
Could anyone point me where I did wrong, please?
Thank you.
UPDATE: Here is the View Model
public class TemplateBuilderViewModel
{
//public int Id { get; set; }
[DisplayName("Template Title")]
public string TemplateTitle { get; set; }
[DisplayName("Paragraph List")]
public string ParagraphTitle { get; set; }
public SelectList ParagraphTitleList { get; set; }
[DisplayName("Paragraph Body")]
[DataType(DataType.MultilineText)]
public string ParagraphText { get; set; }
public int ParagraphId { get; set; }
public int ParagraphOrder { get; set; }
public Dictionary<int, int> ParagraphDictionary { get; set; }
}
And where dict is populated: var dict = [];
for (i = 1; i < counter; i++)
{
var paragraphId = Id;
var order = order;
dict.push({
ParagraphId: paragraphId,
ParagraphOrder: order
});
}
UPDATED JQuery part: After I made changes to below, the problem is I can see goes to controller action, but from the action method parameter templateBuilder, the count of property ParagraphDictionary is 0, which means the Dictionary is not parsed and pass to backend. Other properties like TemplateTitle has value there. Any idea?
var dict = {};
for (i = 1; i < counter; i++) {
var paragraphId = Id;
var order = order;
dict[order] = paragraphId;
}
var templateBuilder = {
TemplateTitle: templateTitle,
ParagraphTitle: "",
ParagraphTitleList: undefined,
ParagraphText: "",
ParagraphId: "",
ParagraphOrder: "",
ParagraphDictionary: dict
};
$.ajax(
{
url: "/TemplateBuilder/Build",
type: "POST",
data: JSON.stringify(templateBuilder),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("successful");
},
error: function (xhr, status, error) {
alert("fail");
alert(error);
}
});