I am using jquery-tmpl and receiving the following JSON data, which I am using for form validation in ASP.NET MVC3:
{"Status":1,"Message":"Oh dear, what have you done. Check the list of errors dude!","Errors":["The Contents field is required.","The Date Created field is required.","The Date Updated field is required.","The Updated By field is required."]}
My template looks like this:
<script id="ResponseTemplate" type="text/x-jquery-tmpl">
{{each(i, error) Errors}}
<li>${error}</li>
{{/each}}
</script>
My JSON POST is as follows:
var data = {
Contents: "This is a test",
DateCreated: "",
DateUpdated: "",
UpdatedBy: "Ben"
};
$.ajax({
url: '@Url.Action("save", "note")',
data: JSON.stringify(data),
type: 'POST',
contentType: 'application/json',
dataType: 'json',
success: function (result) {
alert(result.Errors);
$("#Responses").tmpl(result).appendTo("#ResponseTemplate")
}
});
The data is correct. The alert is showing the Errors array as a string. The template just is not working.
The answer must be simple.
I think you just have
ResponsesandResponseTemplatemixed up:Here’s your example (without the AJAX calls): http://jsfiddle.net/andrewwhitaker/GcqZX/
You could also write your template like this:
And call it like this:
(Not sure if it’s actually any better, but just wanted to point out that you don’t have to use
{{each}}in this case).