Auto complete textbox using web service - asp.net

I have created web service which I am calling from client script. But it shows an error. I can not understand where the error is coming from. I also set break points at different points both in web service and in client script but not encountered those break points. Here is the code that I have written.
Code for Class file
public class GetContacts
{
public int ID { get; set; }
public string Name { get; set; }
public GetContacts()
{
//
// TODO: Add constructor logic here
//
}
public List<GetContacts> FetchContacts()
{
List<GetContacts> ContactList = new List<GetContacts>();
ContactList.Add(new GetContacts() { ID = 1, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 2, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 3, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 4, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 5, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 6, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 7, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 7, Name = "XXX<1111111111>" });
return ContactList;
}
}
Code for web service.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Contacts : System.Web.Services.WebService {
public Contacts () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
public List<GetContacts> FetchContactList(string Name)
{
var Receipent = new GetContacts();
var ContactDetail = Receipent.FetchContacts()
.Where(m => m.Name.ToLower().StartsWith(Name.ToLower()));
return ContactDetail.ToList();
}
}
Code for Default.aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<%--<script src="jQuery.js" type="text/javascript"></script>--%>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "Contacts.asmx/FetchContactList",
data: "{ 'Name': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table width="100%">
<tr>
<td>
Number</td>
<td>
<asp:TextBox ID="txtNumber" runat="server" class="tb"></asp:TextBox>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
Message</td>
<td>
<asp:TextBox ID="txtMsg" runat="server" TextMode="MultiLine"></asp:TextBox></td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSend" runat="server" Text="Send" onclick="btnSend_Click" /></td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
Please tell me where I am making mistakes.

Add [WebMethod] attribute to your FetchContactList

have you implemented the attributes
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
See this for complete reference
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AutoComplete/AutoComplete.aspx

Related

Grid Click event doesn't works after reload

I have DataTable with external button (search) to filter data, It works fine with first time load / page load (refer 1st time click.PNG)
I need to filter table with multiple criteria so added a search button on the same page and called reload function
I search click it re-loads data correctly but grid click event doesn't work after search button click
how to resolve this?
1st time grid click works
ASP.NET page
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<style type="text/css">
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanelSalesOrder" runat="server">
<ContentTemplate>
<div class="row no-gutters">
<div class="col-sm-3">
<select class="custom-select custom-select-sm" runat="server" id="txtCategory">
</select>
</div>
<div class="col-sm-3">
<asp:Button ID="btnSearch" runat="server" Text="Search" CausesValidation="False"
CssClass="btn btn-secondary btn-sm btn-block" OnClick="btnSearch_Click" />
</div>
<div class="col-sm-6">
</div>
</div>
<table id="tblOrder" class="table-striped table-bordered table-hover table-sm" style="width: 100%">
<thead>
<tr style="height: 35px">
<th>Ord.No</th>
<th>Date</th>
<th>Product Name</th>
</tr>
</thead>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="theScript" runat="server">
<script type="text/javascript">
$(document).ready(function () {
fill_table();
$('table tbody').on('click', 'tr', function () {
alert("Data Table clicked");
});
});
function fill_table()
{
var table = $('#tblOrder').DataTable(
{
'bPaginate': true,
'bLengthChange': false,
'bFilter': false,
'bInfo': true,
'bAutoWidth': false,
'responsive': false,
"scrollX": true,
'ajax': {
url: "SalesOrderIssue.aspx/get_PendingOrder",
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
dataSrc: function (data) {
return $.parseJSON(data.d)
}
},
'columns': [
{ data: "ORDER_NO" },
{ data: "ORDER_DATE", type: "date", render: function (data) { return moment(data).format("MM/DD/YYYY"); } },
{ data: "ProductMaster.PRODUCT_NAME" },
{ data: "SizeMaster.SIZE_NAME" },
],
'order': [[1, 'asc']],
'error': function (xhr, status, error) {
alert('Error Occured -' + error);
}
})
}
function reload_data() {
fill_table();
}
</script>
</asp:Content>
Code behind
[WebMethod]
public static string get_PendingOrder()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string strOrderList = serializer.Serialize(_listOrderMasterDTO);
return strOrderList;
}
private void fill_PendingOrder()
{
try
{
var ActiveDate = DateTime.Now;
var startOfMonth = new DateTime(ActiveDate.Year, ActiveDate.Month, 1);
DateTime dtFromDate = Functions.ConvertToDateTime(m_strStartDate);
DateTime dtToDate = Functions.ConvertToDateTime(m_strEndDate);
_listOrderMasterDTO = new OrderMasterService().GetOrderMasterByDateAndSubCatIdList(dtFromDate, dtToDate, "", 0, Convert.ToString(txtCategory.Items[txtCategory.SelectedIndex].Text), Convert.ToString(Session["g_DBNAME"]));
}
catch (Exception ex)
{
Module.ShowError(ex, this, this.Page.GetType());
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
fill_PendingOrder();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("$(function(){");
sb.Append("reload_data();");
sb.Append("});");
ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "", sb.ToString(), true);
}
catch (Exception ex)
{
Module.ShowError(ex, this, this.Page.GetType());
}
}

Asp.Net save drop down list value to dabase with ajax

I have a List view with list of task. Each task have state(Active, Stoped, Complete etc). For displaying states I use EnumDropDownListFor.
View code:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.TaskText)
</td>
<td>
#Html.DisplayFor(modelItem => item.TillDate)
</td>
<td>
#Html.EnumDropDownListFor(modelItem => item.State)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
And Task class:
public class Task
{
public int Id { get; set; }
public string TaskText { get; set; }
public DateTime TillDate { get; set; }
public TaskState State { get; set; }
}
public enum TaskState
{
Active=0,
Stoped,
Complete
}
Now I want to change task state on this view. I mean, I want to select state from dropdown and after selection changed, using ajax, call controller action to save it to database.
How can I do this using ajax?
UPD:
I'v tryed something like this, but can;t figure out how to get task id:
function FillCity() {
var stateId = $('#State').val();
// var taskId=???
$.ajax({
url: '/Home/Edit',
type: "POST",
dataType: "JSON",
data: { State: stateId, taskId: id}
});
}
});
}
The way you tried is absolutely correct, so for the one thing to get the task id, you can make use of hidden variable to store the id and get through javascript like below.
Your changed code:
I'v tryed something like this, but can;t figure out how to get task id:
function FillCity() {
var stateId = $('#State').val();
var taskId=$('#hdntaskid').val()
$.ajax({
url: '/Home/Edit',
type: "POST",
dataType: "JSON",
data: { State: stateId, taskId: id}
});
}
});
}
View Code:
#foreach (var item in Model) {
<tr>
<td>
#Html.HiddenFor(model => model.Id,
new { id= "hdntaskid", Value = #Model.Id})
<td>
<td>
#Html.DisplayFor(modelItem => item.TaskText)
</td>
<td>
#Html.DisplayFor(modelItem => item.TillDate)
</td>
<td>
#Html.EnumDropDownListFor(modelItem => item.State)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
Alternate Js Code:
$(document).ready(function()
{
$("#State").on("change", function()
{
var stateId = $(this).val();
var taskid = $(this).parent().siblings().find('#hdntaskid');
$.ajax({
url: '/Home/Edit',
type: "POST",
dataType: "JSON",
data: { State: stateId, taskId: id}
});
});
});
Hope above information was helpful
thanks
Karthik
You can listen to the change event on the SELECT element, read the selected value and and send it to server (an action method) via ajax where you can save it.
Since we need the task id as well, Let's keep that in data attribute of the SELECT element. We will also use the Url.Action helper method to generate the correct relative path to the server action method which will be called from the ajax code and will save values.
#Html.EnumDropDownListFor(modelItem => item.State, new { data_taskid=item.Id,
data_url=Url.Action("SaveStatus")})
This will render the SELECT element with data attribute "taskid" and "url" ( See the generated html markup by checking the "view source" of the page)
Now the javascript to listen to the change event and make the ajax call
$(function(){
$("SELECT[name='State']").change(function() {
var taskId=$(this).data("taskid");
var stateId=$(this).val();
$.post($(this).data("url"),{ task : taskId, state : stateId},function(re){
// to do : Do something once ajax call is successful
});
});
});
Assuming that you have an action method called SaveStatus which has 2 parameters, task and state
[HttpPost]
public ActionResult SaveStatus(int task,int state)
{
// TO DO : Save the data using the values of task and state
return Json(new { status="success"});
}

KnockoutJS, get data from spring mvc controller and bind it to the view

im trying knockout doing a little test and i have not been able to do this very basic thing with knockout.. i want to return a list from my controller then take that list with my knockout viewmodel and finally bind it to a dropdown in my view.
i have this controller:
#RequestMapping(value="/getUsers", method = RequestMethod.GET)
public List<User> returnUsers(#ModelAttribute User user) {
User user1=new User(), user2, user3 ;
List<User>users=new ArrayList<User>();
user1.setLastName("adsfa");
user1.setName("adfds");
user1.setAge(26);
user2=new User();
user2.setLastName("testLastName2");
user2.setName("testName2");
user2.setAge(45);
user3=new User();
user3.setLastName("testLastName2");
user3.setName("testName3");
user3.setAge(33);
users.add(user1);
users.add(user2);
users.add(user3);
return users;
}
this is my knockout viewmodel:
function viewModel() {
this.name = ko.observable("bob");
this.lastName = ko.observable("smith");
this.age = ko.observable(26);
this.validationMessage = ko.observable();
this.users = ko.observableArray([]);
this.loadUsers(); //with this function call i want to initialize users with my controller data.
}
//this funcion should get the data from my controller
viewModel.prototype.loadUsers = function() {
var tmp = this.users();
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
/*
this.Age = ko.dependentObservable({
read: this.age,
write: function (value) {
if (!isNaN(value)) {
this.age(value);
this.validationMessage("");
}
else {
this.validationMessage("Age must be a number!");
}
},
owner: viewModel
});
*/
var save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
ko.applyBindings(new viewModel());
this is my view:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<h1>Testing</h1>
<p>
<a href="${pageContext.request.contextPath}/specRunner" target=_blank>Launch Test Runner</a>
</p>
First Name: <input type="text" data-bind="
value: name,
valueUpdate : 'afterkeydown'
"/>
<br />
Last Name: <input type="text" data-bind="value:lastName, valueUpdate : 'afterkeydown'" />
<br />
Age: <input type="text" data-bind="value: age, valueUpdate : 'afterkeydown'" />
<Br />
<!--p>Destination country: <select data-bind=" options : availableCountries"></select></p-->
<Br />
<span data-bind="text: validationMessage" style="color:Red"></span>
<div>
<h2>Details:</h2>
<hr />
First Name: <span data-bind="text:name"></span> <br /><br />
Last Name: <span data-bind=" text:lastName"></span><br /><br />
Age: <span data-bind="text:age"></span><br />
<button data-bind="click:save">Submit</button>
<p>Usuarios: <select data-bind="options:users, value:name" type="text"></select></p>
</div>
<script src="resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="resources/js/knockout-3.0.0.js" type="text/javascript"></script>
<script type="text/javascript" src="resources/js/viewModel.js"> </script>
</body>
</html>
don't use this.users() and use prototype for save method also.
viewModel.prototype.loadUsers = function() {
var tmp = this.users;
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
viewModel.prototype.save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
second thing you can return json data directly from controller.
check this sample at fiddle

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>

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/

Resources