Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ShoppingListModel
- {
- public string Name { get; set; }
- public List<ItemModel> Items{ get; set; }
- public ShoppingListModel()
- {
- Items=new List<ItemModel>();
- }
- }
- ShoppingListModel = function(data) {
- var vm = ko.mapping.fromJSON(data);
- return vm;
- };
- @{
- var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
- var data = new JavaScriptSerializer().Serialize(JsonConvert.SerializeObject(Model, jsonSerializerSettings));
- }
- @section scripts {
- <script src="~/App/ShoppingListModel.js"></script>
- <script>
- var vm = ShoppingListModel(@Html.Raw(data));
- ko.applyBindings(vm);
- </script>
- }
- @Html.HiddenFor(model => model.Name, new { @data_bind="value:name"})
- <input type="text" data-bind="value:name"/>
- @Html.HiddenFor(model => model.Items, new { data_bind = "value: items" })
- <tbody data-bind="foreach:items">
- <tr>
- <td>
- <span data-bind="text:name"></span>
- </td>
- <td><span data-bind="text:count"></span></td>
- <td>
- <button class="btn btn-xs" data-bind="click:$parent.remove">
- <i class="fa fa-trash"></i>
- </button>
- </td>
- </tr>
- </tbody>
- <input type="hidden" value="xxx" />
- vm.itemsJson = ko.computed(function() {
- return ko.toJSON(vm.items);
- },this);
- <input name="itemsjson" type="hidden" data-bind="value:itemsJson"/>
- public List<ItemModel> Items{ get; set; }
- public string ItemsJson { get; set; }
- var items=JArray.Parse(model.ItemsJson);
- model.Items = items.
- Select(i => new ItemModel {Name = (string) i["name"], Count = (int) i["count"]})
- .ToList();
- return View(model);
- function YourViewModel() {
- var self = this;
- self.items = ko.observableArray(); //fill it with your stuff;
- self.valueForHiddenField = ko.computed(function() {
- return ko.toJSON(self.items);
- }, this); //use this observable as value of your hidden field
- }
- <form>
- <!-- ko foreach: items -->
- <input type="hidden" data-bind="value: property1, attr: { name: 'Items[' + $index() + '].Property1' }">
- <input type="hidden" data-bind="value: property2, attr: { name: 'Items[' + $index() + '].Property2' }">
- <!-- /ko -->
- </form>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement