我是 Backbone.js 的新手,我一直在学习本教程,现在我对本教程感到满意,接下来我想做的是,而不是像链接中所示的那样从 javascript 设置值。
我想从服务器端传递值,为此我编写了以下代码,
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
List<Person> people = new List<Person>()
{
new Person(){Id = 1, FirstName = "Yasser", LastName = "Shaikh", City = "Mumbai"},
new Person(){Id = 2, FirstName = "Adam", LastName = "Gilchrist", City = "Melbourne"},
new Person(){Id = 3, FirstName = "MS", LastName = "Dhoni", City = "Ranchi"},
new Person(){Id = 4, FirstName = "A", LastName = "Nesta", City = "Milan"},
};
public ActionResult GetTemplateData()
{
var jsonData = new
{
rows = (from m in people select new {
id = m.Id ,
cell = new object[]
{
m.FirstName,
m.LastName,
m.City
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
我正在尝试使用url
属性,但我无法理解如何去做。
请有人指导我得到这个。谢谢 !
更新 1:
我正在使用以下 javascript,请看一下,我已经尝试了您建议的更改.. 请帮我解决这个问题
<script type="text/javascript">
$(document).ready(function () {
// data
var contacts = [];
$.getJSON("@Url.Action("TemplateDemo2", "Home")", function(data){
contacts = data.rows;
});
// Model
var Contact = Backbone.Model.extend({
url:"@Url.Action("TemplateDemo2", "Home")"
});
// Collection
var Directory = Backbone.Collection.extend({
model: Contact
});
// Individual contact view
var ContactView = Backbone.View.extend({
tagName: "div",
className: "contact-container",
template: $("#contactTemplate").html(),
render: function () {
var tmpl = _.template(this.template);
$(this.el).html(tmpl(this.model.toJSON()));
return this;
}
});
// Master View
var DirectoryView = Backbone.View.extend({
el: $("#contacts"),
initialize: function () {
this.collection = new Directory(contacts);
this.render();
},
render: function () {
var that = this;
_.each(this.collection.models, function (item) {
that.renderContact(item);
}, this);
},
renderContact: function (item) {
var contactView = new ContactView({
model: item
});
this.$el.append(contactView.render().el);
}
});
// Instance
var directory = new DirectoryView();
});
</script>
下面是我正在使用的文本模板
<script id="contactTemplate" type="text/template">
<div class="cc">
<h1><%= name %></h1>
</div>
</script>