Using jqmobi 1.2
I'm trying to update the content of a panel with the result of an ajax call.
Following panel will collect the string to search for.
<div id="register_form" class="panel" data-defer="" data-header="default" data-footer="register_footer" data-load="" data-unload="">
<form id="register_data" class="selected">
<fieldset class="scrollable" data-pull-scroller="true">
<legend class="toggelable" >Organization:</legend>
<div id=""class="toggelable">
<label for="seleced_org" >Bezeichnung:</label><br>
<input type="text" id="seleced_org" class="toggelable jq-ui-forms" ><br>
<a class="button icon magnifier" href="javascript:searchOrg();">Search</a>
</div>
</fieldset>
</form>
</div>
The button will call following function, where the success method will add elements to the panel with the id "org_options".
Ajax function:
var FOUNDORGS = [];
function searchOrg() {
var request = $('input[id=seleced_org]').val();
$.ajax({
url: mcTime.ASURL + "/OrgCheck",
dataType: "JSONP",
crossDomain: true,
data: {
maxRows: 12,
name_startsWith: request,
callback: ''
},
success: function(data) {
/*
* server response: [{"organisationId":1,"workerquantity":0,"name":"My_Org","street":"Org_Street 1","zipcode":"45454","city":"Org_City"}]
*/
FOUNDORGS = $.parseJSON(data);
if ($('fieldset[name="options"]').find('.matchingOrgs').length == 0) {
$('fieldset[name="options"]').append('<ul class="mc matchingOrgs"></ul>');
}
var toAppend = $('fieldset[name="options"]').find('.matchingOrgs')[0];
$(toAppend).html('');
for (var i = 0; i < FOUNDORGS.length; i++) {
var obj = FOUNDORGS[i];
var li = $('<li>\n\
<a class="orglink" href="javascript:showOrgDetail(\'' + obj.organisationId + '\',\'' + obj.name + '\');">' + obj.name + '</a>\n\
</li>');
$(toAppend).append(li);
}
$.ui.loadContent('#org_options', false, false, 'slide');
}
});
}
appended div:
<div id="org_options" class="panel" data-header="default" data-footer="register_footer" modal="false" data-unload="">
<fieldset name="options" class="mc scrollable" data-pull-scroller="true">
<legend >Results:</legend>
</fieldset>
</div>
All this works fin in my browser (chrome), and with the XDK emulator but not on my iPhone when using the XDK app-tester.
Any body any idea??
I'm the lead dev on App Framework. There's a bug in the iOS container with handling JSON data from remote servers. There are some posts over at http://forums.html5m.com about it. It's logged internally in our bug tracking system.
thanks,
Ian
Related
Say I am using an
#Html.TetboxFor(m => m.FirstName, new { data_bind= "value:first_name" })
which i am populating from my MVC viewmodel and i want to pass that value to my knockoutJs view model. I have seen the suggestion of creating a javascript object from my viewmodel. I have been able to successfully get the value by telling the viewmodel that
self.first_name = ko.observable($("#FirstName").val())
I tried using the 'text' binding which renders my data from the mvc viewmodel but does not return the data in the knockout view model and the 'value' binding clears my Html helper but does return the data back to the knockout view model. I also tried to use the 'textinput' binding. Is there a better way than what i am using or is the main way of doing this to populate the knockout view model directly from the server? Thanks
I know I will be marked down for giving you an alternate answer but that is ok because it is worth it to share a different way of solving your problem, that is simpler and more powerful.
If you do not mind a suggestion, stay away from ASP.NET MVC Razor templating, it is not powerful, it is tightly coupling your backend to your front in not much of a different way than ASP.NET Web Forms does.
Here as example of the power of KnockoutJs with ASP.NET MVC, but no Razor for binding Model data to View elements, knockoutjs is used entirely instead. A key take away is that the C# Model is built dynamically in KnockoutJs, using knockout.mapping.js. So when you add a new property to your C# model it is automatically available in your Knockout ViewModel.
Here is a snippet of a .cshtml View using no Razor syntax for the form/input model binding:
#using System.Activities.Statements
#using System.Web.Optimization
#model Mvc.Models.ProjectModel
#{
ViewBag.Title = "Start New Project";
Layout = "~/Views/Shared/_BuildLayout.cshtml";
}
#section sideMenuCustomContent{
#Html.Partial("_PartialSidebarPricing")
}
#using (Html.BeginForm("StartSubmit", "Start", null, FormMethod.Post, new { #role = "form", id = "formStart", enctype = "multipart/form-data" }))
{
<input type="hidden" value="#Url.RouteUrl("UploadStep")" data-bind="valueWithInit: 'UrlWithIdUploadStep'" />
<input type="hidden" value="#Url.Action("GetProjectModel", "Start")" data-bind="valueWithInit: 'UrlRootGetProjectModel'" />
<input type="hidden" value="#Url.Action("StyleInfo", "Start")" data-bind="valueWithInit: 'UrlRootStyleInfo'" />
<input type="hidden" value="#Url.Action("GetCoverColorSwatchUrl", "Asset")" data-bind="valueWithInit: 'UrlRootGetCoverColorImage'" />
<div class="row">
<div class="col-lg-6 col-md-6 featuredTextContainer">
<div class="style-hero" >
<h1 class="style-title" data-bind="text: Style.StyleName"></h1>
<div class="style-start-price" >Starting at: <span data-bind="text: Application.FormatCurrency(BookBasePrice())"></span></div>
<div class="style-caption" >
<p data-bind="text: Style.DisplayText" ></p>
</div>
</div>
</div>
<div id="book-options-right-column" class="col-lg-4 col-md-6 build-right-column well-black">
<div class="form-group">
<input id="tbxPrjName" type="text" placeholder="Project Name" data-bind="value: Name" class="couture-input-underline couture-text-white placeholder-center text-center" />
</div>
<div class="form-group">
<input style="width: 80%;" type="text" class="couture-input-underline couture-text-white placeholder-center text-center" placeholder="Estimated Page Count" data-bind="value: PageCountEstimated, valueUpdate: 'afterkeydown'" />
<a data-toggle="popover"
class="popover-250w"
data-placement="bottom"
data-content="Estimate just to help you with pricing, exact page count will be tracked for you. Click the Hamburger Menu in left corner to see current pricing."
data-title="Estimated Page Count">
<i class="glyphicon glyphicon-question-sign"></i>
</a>
</div>
<input type="button" id="stampYes" data-bind="click: OnTextStampingYes, css: { 'selected': TextStamping }" class="btn-couture btn-couture-transparent btn-round" value="Y" />
<input type="button" id="stampNo" data-bind="click: OnTextStampingNo, css: { 'selected': !TextStamping() }" class="btn-couture btn-couture-transparent btn-round" value="N">
</div>
<div class="form-group" data-bind="visible: Style.HasBackCoverOption">
<label>Back Cover Image</label>
<a data-toggle="popover"
class="popover-250w"
data-placement="bottom"
data-content="You’ll be able to upload your back cover image on the next page."
data-title="Back Cover Image">
<i class="glyphicon glyphicon-question-sign"></i>
</a>
<br />
<span>
<input type="button" id="BackCoverYes" data-bind="click: onBackCoverChange, css: { 'selected': CoverImageBack }" class="btn-couture btn-couture-transparent btn-round" value="Y" />
<input type="button" id="BackCoverNo" data-bind="click: onBackCoverChangeNo, css: { 'selected': !CoverImageBack() }" class="btn-couture btn-couture-transparent btn-round" value="N" />
</span>
</div>
</div>
</div>
<div class="form-group">
<div data-bind="visible: !PricingPartialShowFinalTotals()">
<button type="button" class="btn-couture btn-couture-transparent btn-couture-white btn-couture-large" data-bind="text: PricingPartialSubmitBtnText, disable: PricingPartialSubmitLock, click: formSubmit"></button>
</div>
</div>
</div>
</div>
<div class="form-group">
<div data-bind="visible: !PricingPartialShowFinalTotals()">
<button type="button" class="btn-couture btn-couture-transparent btn-couture-white btn-couture-large" data-bind="text: PricingPartialSubmitBtnText, disable: PricingPartialSubmitLock, click: formSubmit"></button>
</div>
</div>
}#*using (Html.BeginForm())*#
#section scripts {
#Scripts.Render("~/bundles/knockout")
#*<script src="/Scripts/knockout.mapping.updateData.js"></script>*#
#Scripts.Render("~/bundles/knockout/build/start")
<script id="document-ready">
var viewModel = {};
$(function() {
pageInit();
}); //document.ready
</script>
<script id="ko-bind-page-init">
function pageInit() {
viewModel = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)), BuildStartViewModelMapping);
ko.applyBindings(viewModel);
viewModel.errors.showAllMessages(false); //ko.validation init
}
</script>
}
And here is part of knockout.mapping.js (~/bundles/knockout/build/start):
var viewModel = {};
var BuildStartViewModel = function (data) {
ko.mapping.fromJS(data, BuildStartViewModelMapping, this);
};
var BuildStartViewModelMapping = {
//'ignore': ['CoverColorName', 'PaperName', 'CoverColorId'],
create: function (options) {
var self = new BuildStartViewModel(options.data);
ko.BaseViewModel.call(self);
ko.BuildCommonViewModel.call(self);
self.IsStartView(true);
/*=================================================*/
//Custom observables not in data
/*=================================================*/
self.AdditionalTextStampingYes = ko.observable(false);
self.OriginalProjectName = ko.observable(self.Name());
/*=================================================*/
self.BuildStartBgClassGet = ko.computed(function () {
var styleName = self.Style.StyleName().toLowerCase();
return 'build-start-bg-' + styleName;
});
self.PageCountEstimated.subscribe(updatePageCount);
function updatePageCount() {
if (validatePageCountEstimated(self.PageCountEstimated())) {
self.PageCount(self.PageCountEstimated());
}
}
/*=================================================*/
//New Style Selected
/*=================================================*/
self.Style.StyleId.subscribe(onStyleIdNew);
function onStyleIdNew() {
if (!self.Style.StyleId())
return;
Application.LoadingDisplayToggle();
var url = $.concatUrl(viewModel.UrlRootGetProjectModel(), viewModel.Style.StyleId());
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
async: true,
success: function (data) {
if (!data)
return;
ko.mapping.fromJS(data, BuildStartViewModelMapping, viewModel);
viewModel.errors.showAllMessages(false); //ko.validation init
//Refresh/Update Style Image
var $styleImage = $('#imgDisplayImage');
$styleImage.attr('src', '');
$styleImage.attr('src', data.Style.DisplayImage);
$('#hdnimage').val(data.Style.DisplayImage);
var $body = $('body');
console.log('TODO: UnComment When we have style images');
//$body.removeClass();
//$body.addClass('cover ' + self.BuildStartBgClassGet());
Application.LoadingDisplayToggle();
},
error: function () {
Application.LoadingDisplayToggle();
}
});
}
/*=================================================*/
self.formSubmit = saveData;
return self;
/*=================================================*/
//saveData/submit
/*=================================================*/
function saveData(data, event) {
//self.Name.isValidating.subscribe(function (isValidating) {
// if (!isValidating && self.errors().length > 0) {
// self.errors.showAllMessages(true);
// return;
// }
//});
//if (self.isValidating()) {
// setTimeout(function () {
// saveData(data, event);
// }, 50);
// return false;
//}
// ko.validation check if valid
if (self.errors().length > 0) {
self.errors.showAllMessages(true);
return;
}
var $form = $(event.currentTarget).closest('form');
if ($form.valid() && self.errors().length === 0) {
var copy = ko.toJS(this);
delete copy.errors;
delete copy.__ko_mapping__;
$.ajax({
url: $form.attr('action'),
type: 'POST',
dataType: 'json',
data: ko.toJSON(copy),
contentType: 'application/json; charset=utf-8',
success: function (response) {
var url = self.UrlWithIdUploadStep();
url = url.substr(0, url.lastIndexOf("/")); //remove id (could be StyleId and not ProjectId if new project)
url = $.concatUrl(url, response); //add project id to url, could be existing or new ProjectId
window.location.href = url;
},
beforeSend: function () {
self.PricingPartialSubmitLock(true);
Application.LoadingDisplayToggle();
},
error: function (result, error, errorThrown) {
self.PricingPartialSubmitLock(false);
Application.LoadingDisplayToggle();
Application.ToastrError(result.responseText);
}
});
}
return false;
};
}
};
And here is Scripts/knockout.mapping.updateData.js, I do not think you will need it to get started with this pattern but I included just in case:
/*
* Extension to the knockoutjs mapping plugin
* http://github.com/janhartigan/knockout-mapping-updatedata
* Requires KnockoutJS and the mapping plugin
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* Jan Hartigan
*/
(function () {
/**
* A function that lets you "update from js" without overriding all the view model properties and methods. You just need to supply
* the viewModel, the original JS model on which you based your data (typically what you'd use in the mapping fromJS method), and the new JS
* object that has the updated information.
*
* #param Object viewModel
* #param Object dataModel
* #param Object jsObject
*
* #return Object (returns the viewModel)
*/
ko.mapping.updateData = function(viewModel, dataModel, jsObject) {
if (arguments.length < 3) throw new Error("When calling ko.updateData, pass: the view model, the data model, and the updated data.");
if (!viewModel) throw new Error("The view model is undefined.");
for (var i in dataModel) {
if (i in jsObject && i in viewModel && typeof dataModel[i] != 'function') {
viewModel[i](jsObject[i]);
}
}
return viewModel;
}
ko.exportSymbol('mapping.updateData', ko.mapping.updateData);
})();
Please, look into my code. I would like to avoid opening a new window in due to watching results. I would like to avoid showing results instead of current content in the same window.
I have thought about using AJAX to show results in Dialog window (JQueryUI)
https://jqueryui.com/dialog/
but I have no idea how? Thank You in advance :)
HTML: result_browser.html
<form class="form" method="post" id="resultbrowserform">
<!--Something-->
<button type="submit" class="btn btn-default"> Apply </button>
</form>
<div id="dialog" title="Details">
<p></p>
</div>
JS:
$(function () { function serializeForm(form){...}
...
$('#resultbrowserform').submit(function () {
$.ajax({
type: 'POST',
url: '/result_browser/data/',
data: serializeForm($('#resultbrowserform')),
success: function (data, status, jqXHR) {
$('#resultbrowsertablecontainer').remove();
data = data.data;
if (!data.length) {
window.alert('No data for selected time period');
return;
}
div = $('<div id="resultbrowsertablecontainer">');
table = $('<table class="table table-striped">');
header = $('<thead>');
header.append($('<tr>')
.append( $('<th>').html('Die Id'))
.append( $('<th>').html('Application'))
.append( $('<th>').html('Result'))
table.append(header);
body = $('<tbody>');
for (i = 0; i < data.length; i++) {
row = $('<tr>');
row.append( $('<td>').html(data[i].die_id));
row.append( $('<td>').html(data[i].application));
row.append( $('<td>').html(data[i].result));
<!--I would like to avoid opening a new window-->
link = $('<a>').attr('target', '_blank').attr('href', '/result_details/' + data[i].result_id + '/').html('Details');
row.append($('<td>').append(link));
body.append(row);
}
table.append(body);
div.append(table);
$('#resultbrowsercontainer').append(div);
}
});
return false;
});
});
Simply remove the target attribute and then it will open inside itself:
<!--I would like to avoid opening a new window-->
link = $('<a>').attr('href', '/result_details/' + data[i].result_id + '/').html('Details');
Trying to search in Wikipedia by user's input but it doesn't work for some reason. First I thought it could be due to cross domain problem. But .ajax should help with that.
Here is codepen: http://codepen.io/ekilja01/pen/pRerpb
Here is my HTML:
<script src="https://use.fontawesome.com/43f8201759.js">
</script>
<body>
<h2 class="headertext">WIKIPEDIA <br> VIEWER </h2>
<div class="row">
<div class="col-10-md">
<input class="searchRequest blink_me" id="cursor" type="text" placeholder="__"></input>
</div>
<div class="searchIcon col-2-md"> </div>
</div>
<div>
<p class=results></p>
</div>
</body>
Here is my jQuery:
$(document).ready(function() {
var icon = "<i class='fa fa-search fa-2x'></i>";
$('#cursor').on("keydown", function() {
$(this).removeClass("blink_me");
var searchIcon = $(".searchIcon");
searchIcon.empty();
if ($(".searchRequest").val().length > 0) {
searchIcon.append(icon);
}
searchIcon.on("click", function() {
console.log("clicked!");
var search = $(".searchRequest").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + search + "&format=json&callback=?";
$.ajax({
dataType: "jsonp",
url: url,
success: function(data) {
$(".results").html(data[0]);
console.log(data[0]);
}
});
});
});
});
What am doing wrong? Please help.
There's an error in the order of load for your js.
The data object contains the text of the results in the array with index 2, which i assume is what you want to show, change it to
$(".results").html(data[2]);
You can check a modified version of your original code here
http://codepen.io/anon/pen/mRmGXG
I'm struggling with this 3 days and can't get my mind around why the first viewModel is working but second isn't , it even doesn't allow me console.log() anything.
My view Models and ko bindings:
// KO View Models
var indexViewModel = {
item: ko.observableArray([]),
cat: ko.observableArray([]),
loadcontent: function () {
alert("inside index function");
$.ajax({
url: '/api/item/all',
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
indexViewModel.item(getArray);
}
});
$.ajax({
url: '/api/category/all',
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
indexViewModel.cat(getArray);
}
});
}
};
var dataReal = null;
var itemViewModel = {
item: ko.observableArray([]),
loadcontent: function (getID) {
alert(getID);
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
itemViewModel.item(getArray);
dataReal = data;
},
error: function (xhr, status) {
switch (status) {
case 404:
alert('File not found');
break;
case 500:
alert('Server error');
break;
case 0:
alert('Request aborted');
break;
default:
alert('Unknown error ' + status);
}
}
});
}
};
var mainViewModel = {
indexPage: indexViewModel,
itemPage: itemViewModel
};
ko.applyBindings(mainViewModel);
My working HTML:
<div id="index-content" data-bind="init: mainViewModel.indexPage.loadcontent(), with: mainViewModel.indexPage">
<div class="item-list" data-bind="foreach: item">
<div class="item-container clearfix">
<div class="item-content clearfix">
<div class="title" data-bind="text: Title">
</div>
<div class="left-side clearfix">
<div class="item-image" data-bind="style: { backgroundImage: 'url(content/u/'+Image+')' }">
</div>
<div class="item-descr">
<div class="body" data-bind="text: Body">
</div>
<div class="item-more-details">
Vairāk...
</div>
</div>
</div>
And the HTML witch even ignores my console.log() calls:
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
int id = ViewBag.id;
}
<div id="item-details-content">
<input type="hidden" id="item-id" value="#id" data-bind=""/>
<div class="item-list" data-bind="init: itemPage.loadcontent(#id), with: itemPage.item">
<div class="item-container clearfix" data-bind="init: console.log($root)">
<div class="item-content clearfix">
<div class="title" data-bind="text: Title">
</div>
<div class="left-side clearfix">
<div class="item-image" data-bind="style: { backgroundImage: 'url(content/u/'+Image+')' }">
</div>
<div class="item-descr">
<div class="body" data-bind="text: Body">
</div>
<div class="item-more-details">
Vairāk...
</div>
</div>
</div>
Questions
What am I doing wrong?
Where is syntax errors?
How can I get console.log() working there?
Maybe there is an alternative to my problem, maybe I'm misunderstanding the concept of KO.js?
Conclusions
I know there is data inside mainViewModel.itemPage.loadcontent($.ajax(data)) because alert() shows it, but it doesn't pass the value to item!
I'm a newbie, total newbie, and if I thought I'am somewhat a decent programmer now I think I am total dumb ass and I am starting to hate KO.js, but I need it very badly!
NOTE: You can see in debug section that index page works just fine.
DEBUG PLACE
Here is published web application
And here is single item page
THANK YOU
Thanks everyone for helping me, I was so frustrated that I even didn't see any more the obvious, thanks again! Cheers!
1) At first glance, I noticed your HTML bindings are referring to mainViewModel. For example:
data-bind="init: mainViewModel.itemPage.loadcontent(#id), with: mainViewModel.itemPage.item
should likely be
data-bind="init: itemPage.loadcontent(#id), with: itemPage.item
You are already bound to mainViewModel
2) For debugging, use this to see what you are bound to in the view.
<pre data-bind="text:ko.toJSON(yourViewModelGoesHere, null, 2)"></pre>
3) The data being returned is not an array, though you are treating it as such.
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
itemViewModel.item(getArray);
dataReal = data;
},
If you create a sample at http://jsfiddle.net we can help you more.
Within the data-bind elements, you are referring to your model relative the the object you specified in the applyBindings() function. In your case, you called applyBindings(mainViewModel), so in the bindings themselves, you refer to its properties, not to mainViewModel itself.
In your non-working HTML, <div class="item-container clearfix" data-bind="console.log($root)"> seems suspicious. What kind of binding is this? It doesn't specify any particular property to bind.
Use your browser's developer tools (Firebug in Firefox, Developer Tools in Chrome/IE...) to see the syntax errors. If there are problems with bindings, you will see them there.
I'm trying to make a list of items (telephones and dependents for a customer), for example, the user could include some number phones and remove others (maybe edit them if it is possible), like a list inside the record of customer.
I'd like to know how can I do it on client side and get the list in server side ?
Is there a jquery plugin or a best pratice to do it?
P.S.: I'm using ASP.Net MVC 2.
Serialise the data into a format like JSON and then send it to the server as a string.
When I had to learn it, these posts were extremely useful.
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
You can serialise a javascript array into a string that ASP.Net can deserialise.
There is a standard called JSON which is good, as it adds nearly no noise on the actual data (like xml does, incrementing a LOT the amount of data to transfer).
You can then use the $.ajax jquery method to send this data to a WebMethod you created (see links) and get an understandable response back.
EDIT:
If you were already inside this stuff, you can simply use the JSON.stringify() method, passing the object/array to serialise in it.
I keep this example around to get me started, just put the proper stuff in the proper files and edit it to match what you are doing:
/* in this case I am using */
available at: http://www.json.org/js.html
function jsonObject()
{
};
var phoneListObject = new jsonObject();
function SaveJsonObject()
{
phoneListObject.Control = new jsonObject();
phoneListObject.Control.CustomerId = $("#CustomerId").val();
phoneListObject.Control.CustomerName = $("#CustomerName").val();
phoneListObject.ListBody.PhonesBlock = new jsonObject();
phoneListObject.ListBody.PhonesBlock.Phone = new Array();
$('#PhonesBlock .Phone').each(function(myindex)
{
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneNumber = $(".PhoneNumber input", this).val();
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneName = $(".PhoneName input", this).val();
});
};
$(function()
{
function SaveCurrentList()
{
SaveJsonObject();
var currentSet = phoneListObject;
var formData = { FormData: currentSet };
phoneListJSON = JSON.stringify(formData);
var FormData = "{ FormData:" + JSON.stringify(phoneListJSON) + "}";
SavePhoneListData(FormData);
};
function SavePhoneListData(phonesData)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: phonesData,
dataFilter: function(data)
{
var msg;
if ((typeof (JSON) !== 'undefined') &&
(typeof (JSON.parse) === 'function'))
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "../../WebServices/ManagePhones.asmx/SaveJson",
success: function(msg)
{
SaveSuccess(msg);
},
complete: function(xhr, textresponse)
{
var err = eval("(" + xhr.responseText + ")");
},
error: function(msg)
{
},
failure: function(msg)
{
}
});
};
$('#btnSave').click(function()
{
SaveCurrentList();
});
});
/* json data snip */
{"FormData":{"Control":{"CustomerId":"12345y6","CustomerName":"Joe Customer"},"PhonesBlock":{"Phone":[{"PhoneNumber":"234-233-2322","PhoneName":"son harry"},{"PhoneNumber":"234-233-2323","PhoneName":"son frank"},{"PhoneNumber":"234-233-2320","PhoneName":"momk"}]}}}
/XML of the form data:/
<FormData>
<Control>
<CustomerId>12345y6</CustomerId>
<CustomerName>Joe Customer</CustomerName>
</Control>
<PhonesBlock>
<Phone>
<PhoneNumber>234-233-2322</PhoneNumber>
<PhoneName>son harry</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2323</PhoneNumber>
<PhoneName>son frank</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2321</PhoneNumber>
<PhoneName>momk</PhoneName>
</Phone>
</PhonesBlock>
</FormData>
/* form layout snip */
<div class="control">
<div class="customer">
<input typeof="text" id="CutomerId" />
<input typeof="text" id="CutomerName" />
</div>
<div class="phoneslist" id="PhonesBlock">
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
</div>
</div>
<input id="buttonSave" class="myButton" type="button" value="Save" />
signature of the web service method:
[WebMethod(EnableSession = true)]
public string SaveJson(string FormData)
{
}