Knockout observables not binding and applyBindings firing twice - asp.net

I had earlier asked this question here which worked in a html file. Now I am trying to put the same in the ASP.NET webform but does not seem to work.
What happens here the first time the page loads ajax call fires which I do not want except when the cursor is moved away from the text box
On Blur I have a popup window that I want to show the data returned from the ajax call. The data does not bind either. What am I doing wrong here.
My Javascript:
<script type="text/javascript">
var self = this;
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
this.SurnameViewModel(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel(Surname) {
var self = this;
self.Surnames = ko.observableArray();
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
$(document).ready(function () {
ko.applyBindings(new SurnameViewModel());
});
</script>
My HTML
<!-- Grey Background -->
<div id="cover"></div>
<!-- Surname Popup -->
<div id="dialog" style="display:none">
My Dialog Content
<br /><input ID="txtSurnameSearch" type="text" />
<br /><input type="button" value="Submit" />
<br />[Close]
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre> //<= just shows the header
<table>
<thead>
<tr>
<th>ID</th>
<th>Family Name</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: Surnames">
<tr>
<td data-bind="value: id"></td>
<td data-bind="value: homename"></td>
</tr>
</tbody>
</table>
</div>
TextBox where the onBlur is called:
<asp:TextBox ID="txtSurname" MaxLength="50" runat="server" Width="127px" class="txtboxes" placeholder="Last Name" onblur="showPopUp();" />
JSON Data returned by the ajax call
{"data":"[{\"id\":3,\"homename\":\"D\\u0027Costa\"}]"}
Edit 1:
If I hard code the values in the ajax call it seems to bind but still fires on page load
data: { "Name":"d", "ChurchID": "17" },

In your view model your Ajax call is inline, not inside a method, so as an instance of its contstructed your AJAX gets fired off. See this code, we create a global variable to hold the instance of your model and then wrap the AJAX call into its on function (method) in your JS. Then you can just call the method on your instance when you need to in your popup code.
var self = this;
var model = new SurnameViewModel();
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
model.GetSurname(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel() {
var self = this;
self.Surnames = ko.observableArray();
self.GetSurname = function(Surname){
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
}
$(document).ready(function () {
ko.applyBindings(model);
});
</script>

Related

Knockoutjs not binding to element

I am kind of new to KnockoutJS and trying to use it.
I am having trouble binding the element using knockoutjs. Please see the fiddle below and help in resolving and correcting me.
It is basically not binding the value to the span element.
http://jsfiddle.net/EpyRA/
HTML:
<div id="taxyear">
<table style="width: 100%;" cellpadding="4" cellspacing="4">
<tr>
<td style="width: 25%">
<span>Name:</span><span data-bind="value: ReturnData.Name"></span>
</td>
</tr>
</table>
</div>
Javascript:
var myWeb = myWeb || {};
$(function () {
(function (myWeb) {
"use strict";
var serviceBase = '../Services/Data.asmx/',
getSvcUrl = function (method) { return serviceBase + method; };
myWeb.ajaxService = (function () {
var ajaxGetJson = function (method, jsonIn, callback) {
$.ajax({
url: getSvcUrl(method),
type: "GET",
data: jsonIn,
dataType: "json",
contentType: "application/json",
success: function (json) {
callback(json);
}
});
},
ajaxPostJson = function (method, jsonIn, callback) {
var test = { "Name": "testRaju", "SourceID": "ABCD" };
//just return data instead of calling for testing
callback(test);
};
return {
ajaxGetJson: ajaxGetJson,
ajaxPostJson: ajaxPostJson
};
})();
} (myWeb));
(function (myWeb) {
"use strict";
myWeb.DataService = {
getReturnData: function (jsonIn, callback) {
myWeb.ajaxService.ajaxPostJson("GetReturnData", jsonIn, callback);
}
};
} (myWeb));
//Constructor for a ReturnData object
myWeb.ReturnData = function () {
this.Name = ko.observable();
this.SourceID = ko.observable();
},
//View Model
myWeb.prdviewmodel = (function () {
var prd = ko.observable();
loadReturnDataCallback = function (jsonReturnData) {
alert(jsonReturnData.Name);
prd = new myWeb.ReturnData()
.Name(jsonReturnData.Name)
.SourceID(jsonReturnData.SourceID);
},
loadReturnData = function () {
myWeb.DataService.getReturnData("{'YearID':'" + 22 + "'}", myWeb.prdviewmodel.loadReturnDataCallback);
};
//public
return {
loadReturnData: loadReturnData,
loadReturnDataCallback: loadReturnDataCallback,
ReturnData: prd
}
})();
//hookup knockout to our viewmodel
myWeb.prdviewmodel.loadReturnData();
ko.applyBindings(myWeb.prdviewmodel);
});
Thanks in Advance,
Sam
I see a couple of minor issues:
When binding against a span, you would want to use the text binding rather than the value binding.
In the AJAX callback, you would want to set the prd observable's value by calling it as a function, rather than setting it as a new value.
In the UI, you can make use of the with binding to ensure that it does not try to bind to a property of the observable, before it has been loaded.
Here is an updated fiddle: http://jsfiddle.net/rniemeyer/Bdz5a/

not updating entity in viewmodel after post request using ajax

I am new to knockout.js and i am using post method to update data into database . Here is my code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SProduct.aspx.cs" Inherits="SProduct" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="body">
<h2>
Knockout CRUD Operations with ASP.Net Form App</h2>
<h3>
List of Products</h3>
<table id="products1">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody data-bind="foreach: Products">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: formatCurrency(Price)">
</td>
<td>
<button data-bind="click: $root.edit">
Edit</button>
<button data-bind="click: $root.delete">
Delete</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
</td>
<td>
</td>
<td>
Total :
</td>
<td data-bind="text: formatCurrency($root.Total())">
</td>
<td>
</td>
</tr>
</tfoot>
</table>
<br />
<div style="border-top: solid 2px #282828; width: 430px; height: 10px">
</div>
<div data-bind="if: Product">
<div>
<h2>
Update Product</h2>
</div>
<div>
<label for="productId" data-bind="visible: false">
ID</label>
<label data-bind="text: Product().Id, visible: false">
</label>
</div>
<div>
<label for="name">
Name</label>
<input data-bind="value: Product().Name" type="text" title="Name" />
</div>
<div>
<label for="category">
Category</label>
<input data-bind="value: Product().Category" type="text" title="Category" />
</div>
<div>
<label for="price">
Price</label>
<input data-bind="value: Product().Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.update">
Update</button>
<button data-bind="click: $root.cancel">
Cancel</button>
</div>
</div>
<div data-bind="ifnot: Product()">
<div>
<h2>
Add New Product</h2>
</div>
<div>
<label for="name">
Name</label>
<input data-bind="value: $root.Name" type="text" title="Name" />
</div>
<div>
<label for="category">
Category</label>
<input data-bind="value: $root.Category" type="text" title="Category" />
</div>
<div>
<label for="price">
Price</label>
<input data-bind="value: $root.Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.create">
Save</button>
<button data-bind="click: $root.reset">
Reset</button>
</div>
</div>
</div>
<script type="text/javascript">
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
function ProductViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");
var Product = {
Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
// Initialize the view-model
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
// debugger;
$.each(data.d, function (index, prd) {
self.Products.push(prd);
})
//Put the response in ObservableArray
}
});
// Calculate Total of Price After Initialization
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
//Add New Item
self.create = function () {
Product.Id="333";
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: 'SProduct.aspx/Add',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{item:" + ko.toJSON(Product) + "}",
success: function (data) {
self.Products.push(data.d);
self.Name("");
self.Price("");
self.Category("");
},
error:function(data)
{
alert("error");
console.log(data.d);
}
});
}
else {
alert('Please Enter All the Values !!');
}
}
//Delete product details
self.delete = function (Product) {
if (confirm('Are you sure to Delete "' + Product.Name + '" product ??')) {
var id = Product.Id;
$.ajax({
url: 'SProduct.aspx/Delete',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{id:" + ko.toJSON(id) + "}",
success: function (data) {
self.Products.remove(Product);
},
error:function(data){
console.log(data.d);
alert('Error');
}
})
}
}
// Edit product details
self.edit = function (Product) {
self.Product(Product);
}
// Update product details
self.update = function () {
var Product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{Product:" + ko.toJSON(Product) + "}",
success: function (data) {
alert("success");
console.log(data.d);
// self.Products.removeAll();
// self.Products(data.d); //Put the response in ObservableArray
self.Product(null);
alert("Record Updated Successfully");
},
error: function (data) {
console.log(data);
}
})
}
// Reset product details
self.reset = function () {
self.Name("");
self.Price("");
self.Category("");
}
// Cancel product details
self.cancel = function () {
self.Product(null);
}
}
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
</script>
</form>
</body>
</html>
Updated
Here is screen shot of my page . when i click on update ajax success function is called, but no change in above table field .
Why do you have to update the item back to the list? You're not doing anything to the properties of the object on the server side are you?
Your edit method should look something like this:
self.edit = function(item) {
self.Product(item);
};
and remove the following code nemesv said.
self.Products.removeAll();
self.Products(data.d); //Put the response in ObservableArray
My first post so be gentle ;)
Response to comment:
change your success to:
success: function (data) {
var product = ko.utils.arrayFirst(self.Products(), function(item) {
return (item.Id == data.d.Id);
}); // You could either update the product object with the new values from data.d or delete it and add a new product object.
for (var p in product ) {
product [p] = data.d[p];
}
self.Product(null);
alert("Record Updated Successfully");
},
Found a bug, it was replacing the observables with native values.
for (var p in product ) {
product [p](data.d[p]);
}
I took the liberty of simplifying the code and removing everything that hasn't anything to do with the update function. The following code example should work. ( I used knockout 2.3.0 and jQuery 1.9.1)
<script type="text/javascript">
function Product(id, name, price, category) {
var self = this;
self.Id = ko.observable(id);
self.Name = ko.observable(name);
self.Price = ko.observable(price);
self.Category = ko.observable(category);
}
function ProductViewModel() {
var self = this;
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
$.each(data.d, function (index, prd) {
var p = new Product(prd.Id, prd.Name, prd.Price, prd.Category);
self.Products.push(p);
});
}
});
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
self.edit = function(product) {
self.Product(product);
};
self.update = function() {
var product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{product:" + ko.toJSON(product) + "}",
success: function (data) {
for (var p in product) {
product[p](data.d[p]);
}
self.Product(null);
alert("Record Updated Successfully");
},
error: function(data) {
console.log(data);
}
});
};
self.reset = function() {
self.Name("");
self.Price("");
self.Category("");
};
self.cancel = function() {
self.Product(null);
};
}
$(document).ready(function() {
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
});
</script>

How to change the default color of validation message in knockoutJS

I have applied validation on HTML page through knockoutJS..when i suppose to click the submit button the validation works well but the message is displaying with black color...I want it to show with Red..Here is a small piece of my View page:
<tr>
<td align="right" style="width: 30%;">
<b>Name :</b>
</td>
<td align="left" style="width: 70%;">
<input data-bind="value: EmployeeName" placeholder="Employee Name" class="txt"
type="text" />
</td>
</tr>
And My View Model (continued from the above):
var EmpViewModel = function () {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.EmployeeCode = ko.observable("").extend({ required: { message: 'Please enter your Employee Code.'} }); //WANT TO CHANGE THIS MESSAGE TEXT COLOR TO RED..
self.EmployeeName = ko.observable("").extend({ required: { message: 'Please enter your Name.'} });
self.Dob = ko.observable("").extend({ required: { message: 'Please enter your Date of Birth.'} });
self.Age = ko.observable("").extend({ number: true, required: { message: 'Please enter your Age.'} });
self.ContactNumber = ko.observable("").extend({ number: true, required: { message: 'Please enter your Contact Number.'} });
self.EmailID = ko.observable("").extend({ email: true, required: { message: 'Please enter your EmailID.'} });
self.Address = ko.observable("").extend({ required: { message: 'Please enter your Address.'} });
self.MaritalStatus = ko.observable("");
self.City = ko.observable("");
self.Is_Reference = ko.observable("");
//The Object which stored data entered in the observables
var EmpData = {
EmpCode: self.EmployeeCode,
EmpName: self.EmployeeName,
Dob: self.Dob,
Age: self.Age,
ContactNumber: self.ContactNumber,
MaritalStatus: self.MaritalStatus,
EmailID: self.EmailID,
Address: self.Address,
City: self.City,
Is_Reference: self.Is_Reference
};
self.errors = ko.validation.group(this, { deep: true, observable: false });
//Declare an ObservableArray for Storing the JSON Response
self.Employees = ko.observableArray([]);
//Function to perform POST (insert Employee) operation
self.save = function () {
// check if valid
if (self.errors().length > 0) {
self.errors.showAllMessages();
return;
}
//Ajax call to Insert the Employee
$.ajax({
type: "POST",
url: "/Exercise/Save/",
data: ko.toJSON(this), //Convert the Observable Data into JSON
contentType: "application/json",
success: function (data) {
alert(data);
window.close();
opener.location.reload(true);
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
}
ko.applyBindings(new EmpViewModel());
You can create a custom message template.
<script type="text/html" id="myCustomTemplate">
<span
class="yourCustomCssClass"
data-bind="if: field.isModified() && !field.isValid(),
text: field.error"></span>
</script>
And configure knockout-validation to use it:
ko.validation.init({ messageTemplate: 'myCustomTemplate' });
Or like described here: https://github.com/ericmbarnard/Knockout-Validation/wiki/Configuration

KnockoutJs mapping JSON to viewmodel

I'm having problem with binding JSON from ASP.net webform webapi to the viewmodel with KnockoutJs. There is no problem with wepapi and mapping to mappedQuickEntries.
Where did I get it wrong? Thanks.
Error:
Error: Unable to parse bindings.
Message: ReferenceError: ItemPartNumb is not defined;
Bindings value: value: ItemPartNumb
View:
<div>
<table border="1" cellpadding="0" cellspacing="0">
<tbody data-bind="foreach: quickEntries">
<tr>
<td data-bind="value: ItemPartNumb"></td>
<td data-bind="value: ItemDescription"></td>
</tr>
</tbody>
</table>
ViewModel:
<script type="text/javascript">
var QuickEntry = function(_itemPartNumb, _itemDescription) {
this.ItemPartNumber = ko.observable(_itemPartNumb);
this.ItemDescription = ko.observable(_itemDescription);
};
function QuickEntriesViewModel () {
var self = this;
self.quickEntries = ko.observableArray([]);
$.ajax({
url: '/DesktopModules/Blah/API/Data/GetTenQuickEntries',
type: 'GET',
dataType: 'json',
success: function (data) {
var mappedQuickEntries = $.map(data, function (item) {
return new QuickEntry(item.ItemPartNumb, item.ItemDescription);
});
self.quickEntries(mappedQuickEntries);
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
};
ko.applyBindings(new QuickEntriesViewModel());
ItemPartNumb vs ItemPartNumber
And you are using the value-binding instead of the text-binding.
http://jsfiddle.net/MizardX/9sqvk/

Partial view render on button click

I have Index view:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<title>MsmqTest</title>
</head>
<body>
<div>
<input type="submit" id="btnBuy" value="Buy" onclick="location.href='#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })'" />
<input type="submit" id="btnSell" value="Sell" onclick="location.href='#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })'" />
</div>
<div id="msmqpartial">
#{Html.RenderPartial("Partial1", Model); }
</div>
</body>
</html>
and partial:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<p>
Items to buy
#foreach (var item in Model.ItemsToBuy)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
<p>
<a>Items Selled</a>
#foreach (var item in Model.ItemsSelled)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
And controller:
public class MsmqTestController : Controller
{
public MsmqData data = new MsmqData();
public ActionResult Index()
{
return View(data);
}
public ActionResult BuyItem()
{
PushIntoQueue();
ViewBag.DataBuyCount = data.ItemsToBuy.Count;
return PartialView("Partial1",data);
}
}
How to do that when i Click one of button just partial view render, now controller wants to move me to BuyItem view ;/
The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:
<script src="#Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:
<input type="button" value="Buy" data-url="#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />
and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:
$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});
or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:
#Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
#Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
and if you want buttons instead of anchors you could use AJAX forms:
#using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
#using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.
Maybe not the solution you were looking for but, I would forget about partials and use Javascript to call the server to get the data required and then return the data to the client as JSON and use it to render the results to the page asynchronously.
The JavaScript function;
var MyName = (function () {
//PRIVATE FUNCTIONS
var renderHtml = function(data){
$.map(data, function (item) {
$("<td>" + item.whateveritisyoureturn + "</td>").appendTo("#msmqpartial");
});
};
//PUBLIC FUNCTIONS
var getData = function(val){
// call the server method to get some results.
$.ajax({ type: "POST",
url: "/mycontroller/myjsonaction",
dataType: "json",
data: { prop: val },
success: function (data) {
renderHtml();
},
error: function () {
},
complete: function () {
}
});
};
//EXPOSED PROPERTIES AND FUNCTIONS
return {
GetData : getData
};
})();
And on the Server....
public JsonResult myjsonaction(string prop)
{
var JsonResult;
// do whatever you need to do
return Json(JsonResult);
}
hope this helps....

Resources