integrating ccavenue payment gateway in rails - ruby-on-rails

I am trying to integrate ccavenue payment gateway in my rails app..But I cant find any proper documentation. All they provide is 4 files for the integration. I cant figure out how to fit all these together.
1) ccavRequestHandler.html.erb
<html>
<head>
<title> Iframe</title>
</head>
<body>
<center>
<%
merchantData=""
working_key="" #Put in the 32 Bit Working Key provided by CCAVENUES.
access_code="" #Put in the Access Code in quotes provided by CCAVENUES.
params.each do |key,value|
merchantData += key+"="+value+"&"
end
crypto = Crypto.new
encrypted_data = crypto.encrypt(merchantData,working_key)
%>
<iframe width="482" height="500" scrolling="No" frameborder="0" id="paymentFrame" src="https://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction&encRequest=<%=encrypted_data %>&access_code=<%=access_code %>"></iframe>
</center>
<script type="text/javascript" src="assets/javascripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('iframe#paymentFrame').load(function() {
window.addEventListener('message', function(e) {
$("#paymentFrame").css("height",e.data['newHeight']+'px');
}, false);
});
});
</script>
</body>
</html>
2) ccavResponseHandler.html.erb
<html>
<head>
<title>Response Handler</title>
<%= csrf_meta_tags%>
</head>
<body>
<%
workingKey=""#Put in the 32 Bit Working Key provided by CCAVENUES.
encResponse=params[:encResp]
crypto = Crypto.new
decResp=crypto.decrypt(encResponse,workingKey);
decResp = decResp.split("&")
%>
<center>
<font size="4" color="blue"><b>Response Page</b></font>
<table border="1">
<tr>
<td><b>Parameter Name</b></td>
<td><b>Parameter Value</b></td>
<%decResp.each do |key|%>
<tr>
<td><%=key.from(0).to(key.index("=")-1)%> </td>
<td><%=key.from(key.index("=")+1).to(-1)%> </td>
</tr>
<%end%>
</table>
</center>
</body>
</html>
3) crypto.rb
#*****************************************************************
# * COMPANY - AVENUES INDIA PVT Ltd.,
#*****************************************************************
#Name of the Program : AES Encryption/Decryption
#Created by : AVENUES INDIA PVT Ltd., TC-Team
#Created On : 16-02-2014
#Version : Version 1.0
#Contribution : eLitmus Evaluation Pvt Ltd
#*****************************************************************
class Crypto < ActiveRecord::Base
INIT_VECTOR = (0..15).to_a.pack("C*")
def encrypt(plain_text, key)
secret_key = [Digest::MD5.hexdigest(key)].pack("H*")
cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
cipher.encrypt
cipher.key = secret_key
cipher.iv = INIT_VECTOR
encrypted_text = cipher.update(plain_text) + cipher.final
return (encrypted_text.unpack("H*")).first
end
def decrypt(cipher_text,key)
secret_key = [Digest::MD5.hexdigest(key)].pack("H*")
encrypted_text = [cipher_text].pack("H*")
decipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
decipher.decrypt
decipher.key = secret_key
decipher.iv = INIT_VECTOR
decrypted_text = (decipher.update(encrypted_text) + decipher.final).gsub(/\0+$/, '')
return decrypted_text
end
end
4) dataForm.html.erb
<html>
<head>
</head>
<body>
<form method="POST" name="customerData" action="/transaction/ccavRequestHandler">
<table width="40%" height="1" border='1' align="center"><caption><font size="4" color="blue"><b>Integration Kit</b></font></caption></table>
<table width="40%" height="100" border='1' align="center">
<tr>
<td>Parameter Name:</td><td>Parameter Value:</td>
</tr>
<tr>
<td colspan="2"> Compulsory information</td>
</tr>
<tr>
<td>Merchant Id :</td><td><input type="text" name="merchant_id" value="2954"/></td>
</tr>
<tr>
<td>Order Id :</td><td><input type="text" name="order_id" value="123654789"/></td>
</tr>
<tr>
<td>Amount :</td><td><input type="text" name="amount" value="1.00"/></td>
</tr>
<tr>
<td>Currency :</td><td><input type="text" name="currency" value="INR"/></td>
</tr>
<tr>
<td>Redirect URL :</td><td><input type="text" name="redirect_url" value="http://merchantdomain/transaction/ccavResponseHandler"/></td>
</tr>
<tr>
<td>Cancel URL :</td><td><input type="text" name="cancel_url" value="http://merchantdomain/transaction/ccavResponseHandler"/></td>
</tr>
<tr>
<td>Language :</td><td><input type="text" name="language" value="EN"/></td>
</tr>
<tr>
<td colspan="2">Billing information(optional):</td>
</tr>
<tr>
<td>Billing Name :</td><td><input type="text" name="billing_name" value="Charli"/></td>
</tr>
<tr>
<td>Billing Address :</td><td><input type="text" name="billing_address" value="Room no 1101, near Railway station Ambad"/></td>
</tr>
<tr>
<td>Billing City :</td><td><input type="text" name="billing_city" value="Indore"/></td>
</tr>
<tr>
<td>Billing State :</td><td><input type="text" name="billing_state" value="MP"/></td>
</tr>
<tr>
<td>Billing Zip :</td><td><input type="text" name="billing_zip" value="425001"/></td>
</tr>
<tr>
<td>Billing Country :</td><td><input type="text" name="billing_country" value="India"/></td>
</tr>
<tr>
<td>Billing Tel :</td><td><input type="text" name="billing_tel" value="9876543210"/></td>
</tr>
<tr>
<td>Billing Email :</td><td><input type="text" name="billing_email" value="person#gmail.com"/></td>
</tr>
<tr>
<td colspan="2">Shipping information(optional)</td>
</tr>
<tr>
<td>Shipping Name :</td><td><input type="text" name="delivery_name" value="Chaplin"/></td>
</tr>
<tr>
<td>Shipping Address :</td><td><input type="text" name="delivery_address" value="room no.701 near bus stand"/></td>
</tr>
<tr>
<td>shipping City :</td><td><input type="text" name="delivery_city" value="Hyderabad"/></td>
</tr>
<tr>
<td>shipping State :</td><td><input type="text" name="delivery_state" value="Andhra"/></td>
</tr>
<tr>
<td>shipping Zip :</td><td><input type="text" name="delivery_zip" value="425001"/></td>
</tr>
<tr>
<td>shipping Country :</td><td><input type="text" name="delivery_country" value="India"/></td>
</tr>
<tr>
<td>Shipping Tel :</td><td><input type="text" name="delivery_tel" value="9595226054"/></td>
</tr>
<tr>
<td>Merchant Param1 :</td><td><input type="text" name="merchant_param1" value="additional Info."/></td>
</tr>
<tr>
<td>Merchant Param2 :</td><td><input type="text" name="merchant_param2" value="additional Info."/></td>
</tr>
<tr>
<td>Merchant Param3 :</td><td><input type="text" name="merchant_param3" value="additional Info."/></td>
</tr>
<tr>
<td>Merchant Param4 :</td><td><input type="text" name="merchant_param4" value="additional Info."/></td>
</tr>
<tr>
<td>Merchant Param5 :</td><td><input type="text" name="merchant_param5" value="additional Info."/></td>
</tr>
<tr>
<td>Promo Code :</td><td><input type="text" name="promo_code" value=""/></td>
</tr>
<tr>
<td>Vault Info. :</td><td><input type="text" name="customer_identifier" value=""/></td>
</tr>
<tr>
<td>Integration Type :</td><td><input type="text" name="integration_type" value="iframe_normal"/></td>
</tr>
<tr>
<td></td><td><INPUT TYPE="submit" value="CheckOut"></td>
</tr>
</table>
</form>
</body>
</html>
These 4 files is the only docs they provides..
I can also see that in html.erb file they want us to put the keys?? Is it safe??
The gem they provide is really outdated and hence didnt even mention about it.. I really cant figure out where to start with this..Can someone give me a rough idea on how to do this???

Related

How can I fetch authenticated data from school homepage?

I want to crawl my authenticated data from university homepage and there are no API calls.
Therefore, I have to send POST data like id and password to server, but I cannot login without clicking login button.
Below is my code of university homepage.
<form action="./_login.php" method="post" autocomplete = "off" onSubmit="return comp()" name="login" >
<!--<form action="https://hisnet.handong.edu/login/_login.php" method="post" autocomplete = "off" onSubmit="return comp()" name="login" >-->
<!-- E-mail¿¡ ÀÖ´Â ¸µÅ©¸¦ Ŭ¸¯ÇÏ¿© À̵¿ÇÏ´Â °æ¿ì, ÀúÀåµÇ´Â °ª 3°¡Áö -->
<input type =hidden name ="part" value ="">
<input type =hidden name ="f_name" value ="">
<input type =hidden name ="agree" value =""> <!-- 2013.10.04 ÃÊ°ú±Ù¹« À̸ÞÀÏ¿¡¼­ °áÁ¦Ã¢À¸·Î ¹Ù·Î À̵¿ÇϱâÀ§ÇØ Ãß°¡ (±èÀÎŹ) -->
<table border="0" cellpadding="0" cellspacing="0" width="285">
<tr>
<td><img src="/2012_images/intro/logbox1.gif" /></td>
</tr>
<tr>
<td height="23" style="text-align:center; background-image:url(/2012_images/intro/logbox2.gif)">
<input type="radio" name="Language" value="Korean" checked>
<a href='#' onkeypress='checkKorean();'><font style='font-size:10pt;'>ÇѱÛ</font></a>
<input type="radio" name="Language" value="English">
<a href='#' onkeypress='checkEnglish();'><font style='font-size:10pt;'>English</font></a>
</td>
</tr>
<tr>
<td style="text-align:center; background-image:url(/2012_images/intro/logbox2.gif)">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td><img src="/2012_images/intro/txt_id.gif" width="61" height="18" /></td>
<td><span style="">
<input type="text" style="color:#000000; height: 16px; width:138px;ime-mode:inactive" name="id" autocomplete="off" tabindex="1" placeholder="¾ÆÀ̵𸦠ÀÔ·ÂÇϽʽÿÀ." value=""/>
</span></td>
</tr>
<tr>
<td height="6" colspan="2"></td>
</tr>
<tr>
<td><img src="/2012_images/intro/txt_pwd.gif" width="61" height="18" /></td>
<td><input type="password" style="color:#000000; height: 16px; width:138px;ime-mode:inactive" name="password" autocomplete="off" tabindex="1" placeholder="Æнº¿öµå¸¦ ÀÔ·ÂÇϽʽÿÀ."></td>
</tr>
</table>
</td>
<td style="padding-left:8px;"><input type="image" src="/2012_images/intro/btn_login.gif" /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td><img src="/2012_images/intro/logbox_line.gif" /></td>
</tr>
<tr>
<td style="text-align:center; background-image:url(/2012_images/intro/logbox2.gif); height:18px;">
<input type="checkbox" id="saveid" name="saveid" value="Y" /> ¾ÆÀ̵ðÀúÀå <a onclick="UserLoginPopUp()" style="cursor:pointer"><font color="#FF0000"><!--<b>* HISNet ·Î±×ÀÎÀÌ ¾ÈµÉ °æ¿ì</b>--></font></a>
</td>
</tr>
<tr>
<td><img src="/2012_images/intro/logbox3.gif" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><img src="/2012_images/intro/line_txt1_1.gif" border=0/><img src="/2012_images/intro/line_txt1_2.gif" border=0/></td>
</tr>
<tr>
<td><img src="/2012_images/intro/line_txt2_1.gif" border=0/><img src="/2012_images/intro/line_txt2_2.gif" border=0/></td>
</tr>
<tr>
<td><img src="/2012_images/intro/line_txt3_1.gif" border=0/><img src="/2012_images/intro/line_txt3_2.gif" border=0/></td>
</tr>
</table>
</form>
I implemented like this.
main() async {
http.post('http://hisnet.handong.edu/login/login.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {'id':'myID','password':'myPassword'})
.then((response){
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
});
}
However, this implementation only fills the form and not click the login button. In this situation, I wanna send my data to server. How can I do that?
I believe here is how you grok the info.
Step 1, navigate to login page.
Step 2, open your browser debugging tools and select network
Step 3, fail or succeed the login to grab the post info
URL: https://hisnet.handong.edu/login/_login.php
POST data:
part
f_name
agree
Language=Korean
id=sadasd
password=asdasd
x=25
y=26
curl 'https://hisnet.handong.edu/login/_login.php' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: https://hisnet.handong.edu/login/login.php' -H 'Content-Type: application/x-www-form-urlencoded' -H 'DNT: 1' -H 'Connection: keep-alive' -H 'Cookie: PHPSESSID=vn4f2mksuv4lfo1i7co2c0e184; NSC_xfcqpsubm_WJQ=ffffffffc8f47f3e45525d5f4f58455e445a4a423660; NSC_ijtofu_ttm=ffffffffc8f47f2145525d5f4f58455e445a4a423660' -H 'Upgrade-Insecure-Requests: 1' --data 'part=&f_name=&agree=&Language=Korean&id=sadasd&password=asdasd&x=25&y=26'
With all of that information, create your login
http.post(https://hisnet.handong.edu/login/_login.php, body: { "part" : null, "f_name" : null, "agree" : null, "Language": "Korean", "id": "sadasd", "password":"asdasd", "x": "25", "y":"26"})
I honestly do no understand what all these fields mean or have a successful attempt, so I cannot verify regardless whether I am supposed to send an int or string. The worst case scenario, you need to use a webbrowser

Display Nested object

I use spring boot with thymeleaf, in a page try to display a form and it's nested object.
My object Factories has
id
name
List
When I display
<form id="factoriesForm" th:object="${factories}" >
...
...
<table id="machinesTable" class="table table-striped table-hover responsive">
<thead>
<tr>
<th th:text="#{name}">Name</th>
<th th:text="#{description}">Description</th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="machine, stat : ${machines}">
<td>
<input type="hidden" th:id="${'machineId-'+stat.index}" th:field="*{machines[__${stat.index}__].id}" />
<input type="text" class="form-control" th:id="${'machineName-'+stat.index}" th:placeholder="#{name.placeholder}" placeholder="Name" th:field="*{machines[__${stat.index}__].name}" />
</td>
<td> <input type="text" class="form-control" th:id="${'machineDescription-'+stat.index}" th:placeholder="#{description.placeholder}" placeholder="Description" th:field="*{machines[__${stat.index}__].description}" /></td>
<td> <i class="fas fa-trash-alt"></i></td>
</tr>
</tbody>
</table>
</form>
My factories has many machines, but none is displayed
Any idea?
change
${factories}
for
*{factories}

Jquery addRow and autocomplete

I have a table I would like to use autocomplete on a column.
(medSearch is the class set for this column)
I use the Jquery's autocomplete code
autocomp_opt={
source: function(request,response){
var myTable = [];
var searchStr = $(".medSearch").val();
if (searchStr.length>2)
{
alert(searchStr);
var soapEnv = "... searchStr.....";
$.ajax(
{
.............
Then I use Cloud Gen's addRow javascript.
$(document).ready(function(){
$(".addRow").btnAddRow(function(row){row.find(".medSearch").autocomplete(autocomp_opt)});
$(".delRow").btnDelRow();
$(".medSearch").autocomplete(autocomp_opt); //end autocomplete
}); //end document. ready
However, the autocomplete does not work properly with newly added row's column.
The user's input in this new row's column is not taken for the autocomplete query.
It always takes the first row's column content as the input.
I think it's because the jQuery always takes the first item which has class '.medSearch'. Then it does not take the current row's user input.
I don't know how to fix it.
Thank you for your help in advance!
My further question:
Actually, this my further question (it is too long for a comment)
I have two more columns with class identifier medCode and medDin, they need to be populated by the autocomplete result:
success: function(xml){
//alert($(xml).text());
//traverse the xml
var xmlItem = $(xml).find("*").eq(0);
//alert($(xmlItem)[0].nodeName);
var xmlMedItemArr = $(xmlItem).children().children().children();
//alert("Phyiscian Items: "+$(xmlPhyItemArr).length);
// go through each of them
$(xmlMedItemArr).each(function()
{
//do what? get each text
var childList = $(this).children();
myTable.push({
label: $(childList[0]).text() + " - " + $(childList[2]).text(),
value: $(childList[0]).text(),
din: $(childList[2]).text(),
code: $(childList[1]).text()
});
});
select: function(event,ui) {
$(".medCode").val(ui.item.code);
$(".medDin").val(ui.item.din);
},
But as the previous problem, after I select an item from the list of autocomplete result, then the two columns of all rows will be set to the same value.
How can this be done correctly?
Thank you very much for your help!
Here is the html for the table part. (we use ebase xi as the platform. It is a drag and drop web development tool. It will generate the html and some of the script automatically. You will see in the html code)
<!----><div class="CTID-1182-_ eb-1182-panel ">
<!---->Current Medications</div>
<!----><table class="CTID-1156-_ eb-1156-tableControl " summary="">
<tr>
<td>
<table class="eb-1156-tableNavRow " style="margin-top:5px;margin-bottom:5px;" summary="" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="99%">
<span class="eb-1156-tableNavRowInfo " style="padding-left:10px;">Displaying 1...1 of 1 records</span></td>
<td width="1%" align="right">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table class="eb-1156-tableContent " summary="" title="">
<colgroup>
<col style="width:20%;"><col style="width:4%;"><col style="width:4%;"><col style="width:7%;"><col style="width:7%;"><col style="width:7%;"><col style="width:7%;"><col style="width:11%;"><col style="width:11%;"></colgroup>
<tr>
<th id="CTID-1156-_-C-1164" class="eb-1156-tableColumnHeader eb-1164-tableColumnHeader ">
Medicine Name</th>
<th id="CTID-1156-_-C-1168" class="eb-1156-tableColumnHeader eb-1168-tableColumnHeader ">
Med code</th>
<th id="CTID-1156-_-C-1170" class="eb-1156-tableColumnHeader eb-1170-tableColumnHeader ">
Med drug identification number</th>
<th id="CTID-1156-_-C-1175" class="eb-1156-tableColumnHeader eb-1175-tableColumnHeader ">
Dosage</th>
<th id="CTID-1156-_-C-1177" class="eb-1156-tableColumnHeader eb-1177-tableColumnHeader ">
Unit</th>
<th id="CTID-1156-_-C-1179" class="eb-1156-tableColumnHeader eb-1179-tableColumnHeader ">
Frequency</th>
<th id="CTID-1156-_-C-1181" class="eb-1156-tableColumnHeader eb-1181-tableColumnHeader ">
Unit</th>
<th id="CTID-1156-_-C-1200" class="eb-1156-tableColumnHeader eb-1200-tableColumnHeader ">
</th>
<th id="CTID-1156-_-C-1196" class="eb-1156-tableColumnHeader eb-1196-tableColumnHeader ">
</th>
</tr>
<tr class="CTID-1156-_-R-0 eb-1156-tableRow eb-1156-tableRow ">
<td class="eb-1156-tableContentCell eb-1164-tableColumn " headers="CTID-1156-_-C-1164"><div class="eb-1164-Editor " style="display:inline-block;zoom:1;*display:inline;">
<input id="CTID-1164-_-C-0" class="CTID-1164-_-C-0 eb-1156-tableContentData eb-1164-EditorInput medSearch" type="text" name="CTRL:1164:_:C:0" size="50" maxlength="128" title="Medicine Name"></div>
</td>
<td class="eb-1156-tableContentCell eb-1168-tableColumn " headers="CTID-1156-_-C-1168"><div class="eb-1168-Editor " style="display:inline-block;zoom:1;*display:inline;">
<input id="CTID-1168-_-C-0" class="CTID-1168-_-C-0 eb-1156-tableContentData eb-1168-EditorInput medCode" type="text" name="CTRL:1168:_:C:0" size="5" maxlength="32" title="Med code"></div>
</td>
<td class="eb-1156-tableContentCell eb-1170-tableColumn " headers="CTID-1156-_-C-1170"><div class="eb-1170-Editor " style="display:inline-block;zoom:1;*display:inline;">
<input id="CTID-1170-_-C-0" class="CTID-1170-_-C-0 eb-1156-tableContentData eb-1170-EditorInput medDin" type="text" name="CTRL:1170:_:C:0" size="5" maxlength="64" title="Med drug identification number"></div>
</td>
<td class="eb-1156-tableContentCell eb-1175-tableColumn " headers="CTID-1156-_-C-1175"><div class="eb-1175-Editor " style="display:inline-block;zoom:1;*display:inline;">
<input id="CTID-1175-_-C-0" class="CTID-1175-_-C-0 eb-1156-tableContentData eb-1175-EditorInput " type="text" name="CTRL:1175:_:C:0" size="5" maxlength="10" title="Dosage"></div>
</td>
<td class="eb-1156-tableContentCell eb-1177-tableColumn " headers="CTID-1156-_-C-1177"><div class="eb-1177-Editor " style="display:inline-block;zoom:1;*display:inline;">
<select id="CTID-1177-_-C-0" class="CTID-1177-_-C-0 eb-1156-tableContentData eb-1177-EditorInput " name="CTRL:1177:_:C:0" title="Unit"><option selected="selected" value="">Please select</option><option value="109">mg</option><option value="110">ml</option></select></div>
</td>
<td class="eb-1156-tableContentCell eb-1179-tableColumn " headers="CTID-1156-_-C-1179"><div class="eb-1179-Editor " style="display:inline-block;zoom:1;*display:inline;">
<input id="CTID-1179-_-C-0" class="CTID-1179-_-C-0 eb-1156-tableContentData eb-1179-EditorInput " type="text" name="CTRL:1179:_:C:0" size="5" maxlength="64" title="Frequency"></div>
</td>
<td class="eb-1156-tableContentCell eb-1181-tableColumn " headers="CTID-1156-_-C-1181"><div class="eb-1181-Editor " style="display:inline-block;zoom:1;*display:inline;">
<select id="CTID-1181-_-C-0" class="CTID-1181-_-C-0 eb-1156-tableContentData eb-1181-EditorInput " name="CTRL:1181:_:C:0" title="Unit"><option selected="selected" value="">Please select</option><option value="112">per day</option><option value="113">per 4 hours</option></select></div>
</td>
<td class="eb-1156-tableContentCell eb-1200-tableColumn " headers="CTID-1156-_-C-1200"><input class="CTID-1200-_-C-0 eb-1200-Button addRow" type="submit" name="CTRL:1200:_:D:0" value="Add" title=""></td>
<td class="eb-1156-tableContentCell eb-1196-tableColumn " headers="CTID-1156-_-C-1196"><img class="eb-1196-Image delRow" src="shared/uohi/images/delete_icon.gif" alt="" title="">
</td>
</tr>
</table>
</td>
</tr>
</table>
Use:
var searchStr = request.term;
instead of what you currently have.
The existing code:
var searchStr = $(".medSearch").val();
Reads the value of the first element that meets the selector .medSearch
Thank you for all your help.
I have the correct value now by using the following code:
$(this).closest('tr').find(".medCode").val(ui.item.code);
$(this).closest('tr').find(".medDin").val(ui.item.din);
Thanks,
Xiaoli

Knockout with class scoped properties

I am using Knockout and have the ViewModel bound to my data object in my ASP.Net MVC 4 project quite nicely like so:
$(document).ready(function() {
properties = #Html.Raw(Json.Encode(Model));
selectedProperty = properties[0];
viewModel = { properties: ko.mapping.fromJS(#Html.Raw(Json.Encode(Model))), selectedProperty: ko.observable()};
viewModel.setItem = function(item) {
viewModel.selectedProperty(item);
}
ko.applyBindings(viewModel);
Now I want to refactor my JavaScript so that the logic is encapsulated inside a class:
RealEstate.Search = function (properties) {
this.properties = properties;
this.selectedProperty = this.properties[0];
this.viewModel = { properties: ko.mapping.fromJS(this.properties), selectedProperty: ko.observable()};
this.viewModel.setItem = function(item) {
viewModel.selectedProperty(item);
}
ko.applyBindings(this.viewModel);
}
And I am instantiating that object in my HTML page like so:
$(document).ready(function() {
search = new RealEstate.Search(#Html.Raw(Json.Encode(Model)));
}
Now, I am getting the following error:
Error: Unable to parse bindings.
Message: ReferenceError: 'properties' is undefined;
Bindings value: foreach: properties
Here is the snipped HTML for the table bound to the ViewModel:
<div id="divDataTable" data-bind="with: properties">
<table id="dataTable" class="tablesorter">
<thead>
<tr>
<th>Address
</th>
<th>
Suburb
</th>
<th>Price
</th>
<th>Beds
</th>
<th>Baths
</th>
<th>Days Listed
</th>
</tr>
</thead>
<tbody data-bind="foreach: properties">
<tr data-bind="click: $root.setItem">
<td>
<label data-bind="text: $data.Street"></label>
<input data-bind="attr: { value : $index(), id : $index(), name : $index() }" type="hidden" />
</td>
<td data-bind="text: $data.Suburb"></td>
<td data-bind="text: $data.PriceFormatted"></td>
<td data-bind="text: $data.NumOfBedrooms"></td>
<td data-bind="text: $data.NumOfBathrooms"></td>
<td data-bind="text: $data.DaysListed"></td>
</tr>
</tbody>
</table>
</div>
</section>
<div id="divProperty">
<aside class="float-right" data-bind="with: selectedProperty">
<table>
<tr>
<td>
<label data-bind="text: $data.Street"></label>
</td>
<td>
<label data-bind="text: $data.PriceFormatted"></label>
</td>
</tr>
<tr>
<td colspan="2">
<img src="#" /></td>
</tr>
<tr>
<td>Beds:
<label data-bind="text: $data.NumOfBedrooms"></label>
</td>
<td>On OZMite:
<label data-bind="text: $data.DaysListed"></label>
</td>
</tr>
<tr>
<td>Baths:
<label data-bind="text: $data.NumOfBathrooms"></label>
</td>
<td>Year built:</td>
</tr>
</table>
</aside>
I would appreciate it if someone could shed some light on what I am doing wrong.
With the data-bind="with: properties" you are already "in the context" of the properties property inside your div.
So when you write <tbody data-bind="foreach: properties"> KO tries to find the properties property inside your properties array.
What you need is to use to reference the current binding context with the $data.
So your foreach should look like this:
<tbody data-bind="foreach: $data">
...
</todby>

Knockout Validation is not working

It may be the easiest question but I am not able to resolve this. The validation on my page is not working. Everytime I am submitting the page leaving all the input fields blank, an alert is generated saying 'Failed'. And if I enter all the fields with some value data is successfully submitted.
Here is my HTML :
#{
ViewBag.Title = "Exercise10";
}
<html>
<head>
<script src="../../Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.2.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
<link href="../../Content/ExerciseStyle.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/Popup.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery- ui.css" />
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<script src="../../Scripts/DatePicker.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.validation.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-validator.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-validator-extensions.js" type="text/javascript"></script>
<link href="../../Scripts/extensions.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" method="post">
<div id="MainArea">
<table id="tbllist" align="center" style="margin-left: 15px; width: 96%; margin- right: 15px;">
<tr>
<th colspan="3" align="left">
<div id="title_p">
Enter Following Entries</div>
</th>
</tr>
<tr>
<td align="right" style="width: 40%;">
<b>Name :</b>
</td>
<td align="left" style="width: 17%;">
<input data-bind="value: EmployeeName" placeholder="Employee Name" class="txt"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Emp# :</b>
</td>
<td align="left">
<input data-bind="value: EmployeeCode" placeholder="Employee Code" style="width: 200px;"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Date of Birth :</b>
</td>
<td align="left">
<input data-bind="value: Dob" id="datepicker" placeholder="Date of Birth" style="width: 200px;"
type="text" /><span>(dd/mm/yyyy)</span>
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Age (18-60):</b>
</td>
<td align="left">
<input data-bind="value: Age" style="width: 200px;" placeholder="Age Range (18-60)"
type="number" min="18" max="60" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Contact Number :</b>
</td>
<td align="left">
<input data-bind="value: ContactNumber" placeholder="Contact Number" style="width: 200px;"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Email :</b>
</td>
<td align="left">
<input data-bind="value: EmailID" placeholder="Email ID" style="width: 200px;"
type="email" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Address :</b>
</td>
<td align="left">
<input data-bind="value: Address" placeholder="Address" style="width: 200px;"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>City :</b>
</td>
<td align="left">
<select data-bind="value: City" style="width: 200px;">
<option value="Noida">New Delhi</option>
<option value="Noida">Noida</option>
<option value="Noida">Mumbai</option>
</select>
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Marital Status :</b>
</td>
<td align="left">
<input data-bind="checked: MaritalStatus" checked="checked" name="rdb" type="radio" /><span>UnMarried</span>
<input data-bind="checked: MaritalStatus" checked="checked" name="rdb" type="radio" checked="checked" /><span>Married</span>
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Any Employee Reference :</b>
</td>
<td align="left">
<input data-bind="checked: Is_Reference" type="checkbox" />yes
</td>
<td align="left">
</td>
</tr>
</table>
<table style="width: 99%; margin-right: 20px; padding: 5px;">
<tr align="right">
<td>
<button data-bind="click :$root.save" class="button">Save</button>
<input type="button" id="btnCancel" class="button" value="Cancel" onclick="JavaScript:closePopup();" />
</td>
</tr>
</table>
</div>
</form>
And My View Model (continued from the above):
<script type="text/javascript">
//....................................................//
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: true });
self.EmployeeName = ko.observable("").extend({ required: { message: 'Please supply your Name.'} });
self.Dob = ko.observable("");
self.Age = ko.observable("").extend({number :true});
self.ContactNumber = ko.observable("");
self.EmailID = ko.observable("");
self.Address = ko.observable("");
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
};
//Declare an ObservableArray for Storing the JSON Response
self.Employees = ko.observableArray([]);
//Function to perform POST (insert Employee) operation
self.save = function () {
//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);
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
}
ko.applyBindings(new EmpViewModel());
</script>
Knockout-validation shows validation messages only if the fields are modified. Therefore you should check on submit if all fields are valid and show all errors if not.
self.errors = ko.validation.group(this, { deep: true, observable: false });
//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);
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
I have created a fiddle to show that: http://jsfiddle.net/delixfe/tSzYf/2/

Resources