When i select CheckBox().I need to update its value into DB - MVC2,AJAx,JQuery - asp.net-mvc-2

Please find the code which i tried to update the DB using MVC2.But unable to update
View Page with Ajax Code
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$('#cbID').click(function(){
$.ajax({ url: 'Home/About',
type: 'POST',
data: { checkbox: $('#cbID').attr('checked') },
success: function(o) { alert('saved'); }
});
</script>
<div class="bgDiv">
<input id="cbID" type="checkbox" name="SelectedObject" value="cbValue" />
Controller page code
public ActionResult About(string str)
{
AboutModels ObjAM = new AboutModels();//model class name
polloptions = ObjAM.dbValue(str);//call the model function to udate the table
return View();
}
Please advice

you should either declare your event handler in ready function or declare it with live or delegate methods like
<script language="javascript" type="text/javascript">
$(function(){
$('#cbID').click(function(){
$.ajax({ url: 'Home/About',
type: 'POST',
data: { checkbox: $('#cbID').attr('checked') },
success: function(o) { alert('saved'); }
});
});
});
</script>
the problem is that your script is running before the required checkbox is rendered so putting it in ready will wait until document is ready or live will bind it on document level where the event will reach through propogation

Related

Meteor server api using iron router returns HTML not the response

I have a simple Meteor app just the basic meteor create test. I want to be able to route traffic to the "/" directory to a template.
I want to be able to route data from a facebook web-hook to a simple js response.
My issue is that when I fire the web-hook URL using postman it returns HTML and not my response.
I've tried many different options for other posts I have read but now have the most basic version to just get it working.
Here is the code I've used
main.html
<head>
<title>test</title>
</head>
<body>
</body>
<template name="home">
<form class="new-message">
<input type="text" name="message" placeholder="Testing">
</form>
</template>
main.js:
import { Meteor } from 'meteor/meteor';
import { Router } from 'meteor/iron:router';
import { Template } from 'meteor/templating';
import './main.html';
Router.route('/', function () {
this.render('home');
});
Router.route('/webhooks/facebook', function() {
var request = this.request;
var response = this.response;
response.end('webhook was called');
}, {
where: 'server'
});
All other files are exactly how they are created with meteor create.
I'm on Meteor version 1.8.1
I'm using postman to test the web-hook this is the created GET URL:
https://------.ngrok.io/webhooks/facebook?hub.verify_token=mytoken&hub.challenge=1234567&hub.mode=subscribe
code omitted to keep ngrok from getting slammed.
This is the response I'm getting:
<html>
<head>
<link rel="stylesheet" type="text/css" class="__meteor-css__"
href="/merged-stylesheets.css?hash=6b1f9f6fb78291ae58da8ec4f36476931155453c">
<title>simplechat</title>
</head>
<body>
<script type="text/javascript">
__meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.8.1%22%2C%22meteorEnv%22%3A%7B%22NODE_ENV%22%3A%22development%22%2C%22TEST_METADATA%22%3A%22%7B%7D%22%7D%2C%22PUBLIC_SETTINGS%22%3A%7B%7D%2C%22ROOT_URL%22%3A%22http%3A%2F%2Flocalhost%3A3000%2F%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22autoupdate%22%3A%7B%22versions%22%3A%7B%22web.browser%22%3A%7B%22version%22%3A%22b22f1ad86c0a904c992885256b7de72ed2863e1d%22%2C%22versionRefreshable%22%3A%22a580e09175421ec6994fc6da61a0413f3a15d2b1%22%2C%22versionNonRefreshable%22%3A%22fc4ded0006de942fe57524f94d500abeb4569d6f%22%7D%2C%22web.browser.legacy%22%3A%7B%22version%22%3A%222571a76ffc344fbc5b40ade303255cbbc59e2682%22%2C%22versionRefreshable%22%3A%22a580e09175421ec6994fc6da61a0413f3a15d2b1%22%2C%22versionNonRefreshable%22%3A%22dc1e886b7786e303655c010220e9f502e82dcf1c%22%7D%7D%2C%22autoupdateVersion%22%3Anull%2C%22autoupdateVersionRefreshable%22%3Anull%2C%22autoupdateVersionCordova%22%3Anull%2C%22appId%22%3A%22zqskgg1xifoj.hlnqbjmcma6f%22%7D%2C%22appId%22%3A%22zqskgg1xifoj.hlnqbjmcma6f%22%2C%22isModern%22%3Afalse%7D"))
</script>
<script type="text/javascript" src="/packages/meteor.js?hash=857dafb4b9dff17e29ed8498a22ea5b1a3d6b41d"></script>
<script type="text/javascript" src="/packages/meteor-base.js?hash=29010b127daf4ebacaaf9db9b8a61487e57d7d86">
</script>
<script type="text/javascript" src="/packages/mobile-experience.js?hash=2751f9ec11102d1106042c462b340c3fcfcb1990">
</script>
<script type="text/javascript" src="/packages/modules-runtime.js?hash=d3c3e5d67c95f97a60888bda7373292efad3be5e">
</script>
<script type="text/javascript" src="/packages/modules.js?hash=e8b7455d5562fec1444a3c6882cdc6639055cfca"></script>
<script type="text/javascript" src="/packages/modern-browsers.js?
<script type="text/javascript" src="/packages/autoupdate.js?hash=6d56c0f3a885390c688b4f3f893d96d1280fd0ee"></script>
---- Cut out all of the other script calls to keep this short -----
<script type="text/javascript" src="/app/global-imports.js?hash=1f8a1ae2e343994912f72f1dc6eec1ca7df24cae"></script>
<script type="text/javascript" src="/app/app.js?hash=70cfa37cd2f85e533f69d7312d02ef8984eae01a"></script>
</body>
</html>
So basically it returns HTML.
I'm sure I'm missing something simple.
Thanks in advance for you help. Usually I wait till I have exhausted all other options before posting here. And I'm sure I have tried every other example given here on StackOverflow.
My desired result is simple to just return a HTTP response "webhook was called" instead of the HTML garbage.
You could use somethings like this :
Router.map(function(){
this.route("routeName", {path: "/url/:param1/:optionalParam?,
where: "server",
action: function(){
var param = this.params.param1;
this.response.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
//authenticate call and decrypt body
if (this.request.method == 'POST') {
//do something
}
if (this.request.method == 'GET') {
//do something
}
}
});
this.route("abc", {path: "/api/get/user/activity/:temp1",
where: "server",
action: function(){
//proceed as above
}
});
});
For help, read through https://iron-meteor.github.io/iron-router/#server-routing
The router file should be saved inside the server folder (for server-side routes)
Haven't used iron route in a long time but from what I remember you want to change your server side route to the following as it is for restful routes.
Router.route('/webhooks/facebook', { where: 'server' })
.get(function () {
// GET
})
.post(function () {
// POST
})
.put(function () {
// PUT
})
For others who have been struggling getting both server and client routes to work on the same Meteor app here is the solution.
Iron routers newest version requires all server side routes to be on the server side and you must fire them from the startup.
All client routes are added on the client side and included in the main.js on the client side.
My simple test was this:
meteor create test
Then in clients/main.html replace the current code and add a simple template as follows:
<head>
<title>newroutetest</title>
</head>
<body>
</body>
<template name="home">
<h1>Home</h1>
</template>
Then in the client/main.js add your client routes as follows:
import { Template } from 'meteor/templating';
import './main.html';
Router.route('/', {
template: 'home'
});
Now we setup the server side route in the file server/main.js you add the route in the startup section as follows:
import { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
Router.route('/webhook', function () {
var req = this.request;
var res = this.response;
res.end('hello from the server\n');
}, {where: 'server'});
});
That's It
I hope this helps others who have been struggling with this.

kendo mvvm binding within a template

I am trying to kendo mvvm bind within a template. Template variables are working but none of the MVVM stuff is.
<div id="list"></div>
<script id="template" type="text/x-kendo-template">
<div>
<button data-bind="visible: alreadyAttending, click: onClick">
Your id is ${ID}
</button>
</div>
</script>
var data = [];
data[0] = { alreadyAttending: true, ID: 1, onClick: function() { alert("Click 1"); }};
data[1] = { alreadyAttending: false, ID: 2, onClick: function() { alert("Click 2"); }};
$("#list").kendoListView({
dataSource: data,
template: kendo.template($("#template").html())
});
Fiddle available here: https://jsfiddle.net/q99ufo3c/5/
You can see the buttons are replaced with values from the data array, but visibility and click events are not wired up. I'm not sure what I'm missing. Does anyone know if this is supported?
You need to define some data attribute to the div element so that Kendo can bind it correctly to your View Model.
data-role="listview" - defines a listview component;
data-template="yourtemplateid" - defines the template to be used;
data-bind="source: dataSource" - defines what is the data
source of the listview component;
In the Javascript you need to have a Model that represents your object that will be in the data source of the list view. I created one called vm and I have chosen to use the ObservableObject extend method because it is useful when you want to create an object with default values, such as the onClick method.
Please, take a look at the Snippet below.
(function() {
var vm = kendo.data.ObservableObject.extend({
init: function(values) {
var defaultValues = {
alreadyAttending: false,
ID: null
};
kendo.data.ObservableObject.fn.init.call(this, $.extend({}, defaultValues, values));
},
onClick: function() {
alert(this.get("ID"));
}
});
var source = [
new vm({
alreadyAttending: true,
ID: 1
}),
new vm({
alreadyAttending: false,
ID: 2
})
];
var mainViewModel = kendo.observable({
dataSource: source
});
kendo.bind($("#list"), mainViewModel);
})();
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2016.2.504/js/kendo.all.min.js"></script>
</head>
<body>
<div id="list" data-role="listview" data-template="template" data-bind="source: dataSource"></div>
<script id="template" type="text/x-kendo-template">
<div>
<button data-bind="visible: alreadyAttending, click: onClick">
Your id is #:ID#
</button>
</div>
</script>
</body>
</html>

Phonegap App not including javascript files

Javascript files are not being pulled into my Phonegap app. This is a recent problem that is quite frankly driving me insane. This is the top of my index.html file:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD90W6MypWGP6s4luD2kQHhZ9IFQrfr04g&sensor=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/facebook.js"></script>
<script type="text/javascript">
app.initialize();
</script>
This is my facebook.js file that I'm trying to pull in:
$(document).on('ready' , function(){
console.log('ready')
function onDeviceReady(){
console.log('test')
var plugin = new CC.CordovaFacebook();
plugin.init('***************', 'myapp',
['email'],
function(response){console.log(response)},
function(failure){console.log(failure)});
var loginButton = $('#login-with-facebook');
loginButton.on('click' , function(e){
e.preventDefault();
plugin.login(function(token) {
console.log("Access token is: " + token);
}), function(failure){console.log(failure)});
})
}
if (window.cordova.logger) {window.cordova.logger.__onDeviceReady();};
onDeviceReady();
document.addEventListener("deviceready", onDeviceReady, false);
})
I can't console.long anything in the facebook.js file. What's driving me even more crazy is that it's worked on occasion. Are my files out of order? Also, I only seem to be running into this issue after installing one of the cordova facebook plugins. Does anybody know what's going on here?
Because you define your onDeviceReady function inside an anonymous event handler function, it won't be available until the DOM is loaded (and shouldn't only be accessible from within the event handler. This would only work properly if the device is ready before the DOM loads and only because onDeviceReady is manually invoked in the onDocumentReady event handler. Replace your facebook.js with the following.
function onDeviceReady(){
console.log('test')
var plugin = new CC.CordovaFacebook();
plugin.init('443530475777959', 'spencerspiegelapp',
['email'],
function(response){console.log(response)},
function(failure){console.log(failure)});
var loginButton = $('#login-with-facebook');
loginButton.on('click' , function(e){
e.preventDefault();
plugin.login(function(token) {
console.log("Access token is: " + token);
}), function(failure){console.log(failure)});
})
}
$(document).on('ready' , function() {
console.log('ready')
document.addEventListener("deviceready", onDeviceReady, false);
if (window.cordova.logger) {
window.cordova.logger.__onDeviceReady();
}
});

dialog does not come up after uploading asp.net mvc 2

my dialog does not popup after successfull upload? the upload works fine but $("#dialog-confirm").dialog does not work?
<h2>
upload Data</h2>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="../../Scripts/jqueryform.js" type="text/javascript"></script>
<script src="../../Scripts/jblock.js" type="text/javascript"></script>
<script src="../../Content/jquery-ui-1.8.12.custom/js/jquery-ui-1.8.12.custom.min.js"
type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.8.12.custom/css/ui-lightness/jquery-ui-1.8.12.custom.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$("#ajaxUploadForm").block({ message: '<h1><img src="/Content/busy.gif" /> uploading file...</h1>' });
},
success: function (result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, result.message);
//alert(result.message);
//does not popup??
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Ok":
function () {
alert('ok');
$(this).dialog("close");
}
,
Cancel: function () {
$(this).dialog("close");
}
}
});
},
error: function (xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Home")%>" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload a file</legend>
<label>
File to upload:
<input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
</form>
public FileUploadJsonResult AjaxUpload(HttpPostedFileBase file)
{
// TODO: Add your business logic here and/or save the file
System.Threading.Thread.Sleep(2000); // Simulate a long running upload
// Return JSON
return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I see that you are using the jquery.form plugin for AJAXifying the form and returning JSON from your controller action. Here's what the documentation says about this scenario:
Since it is not possible to upload
files using the browser's
XMLHttpRequest object, the Form Plugin
uses a hidden iframe element to help
with the task. This is a common
technique, but it has inherent
limitations. The iframe element is
used as the target of the form's
submit operation which means that the
server response is written to the
iframe. This is fine if the response
type is HTML or XML, but doesn't work
as well if the response type is script
or JSON, both of which often contain
characters that need to be repesented
using entity references when found in
HTML markup.
To account for the challenges of
script and JSON responses, the Form
Plugin allows these responses to be
embedded in a textarea element and it
is recommended that you do so for
these response types when used in
conjuction with file uploads.
So for this to work the response from the server needs to look like this:
<textarea>{ message: 'file uploaded successfully' }</textarea>
Is it what this custom FileUploadJsonResult is doing in your controller action?

MVC2 Client side validation within Jquery modal dialog

Using MVC2 I currently have a view creating a jquery dialog box containing an Edit partial view. On submit I am looking for it to perform client side validation on the Email class which has a required data annotation attribute for email address. Server side validation works fine but I want the user to have to fix the error in the modal dialog.
Below is the code
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
<div>
<label for="EmailAddress">
Email Address :
</label>
<%= Html.TextBoxFor(model => model.Email.EmailAddress)%>
<%= Html.ValidationMessageFor(model => model.Email.EmailAddress)%>
</div>
Scripts I am loading up are
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.3.2.min.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jqueryUI/js/jquery-ui-1.7.2.custom.min.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Splitter/splitter-1.5.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Scripts/Start.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Scripts/extended/ExtendedControls.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery.validate.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/MicrosoftMvcJQueryValidation.js")%>"></script>
Looking at the html generated I am not getting any of the JSON data generated for the client side validation to work.
Any solutions gladly appreciated. S
I strongly recommend you to use jquery validation script.
jquery.validate.js has all the features for client-side validation within a jquery dialog.
First of all, add the jquery.validate.js to your Site.Master :
<script src="/Scripts/Using/jquery.validate.js" type="text/javascript"></script>
and then write your script something like that :
<script type="text/javascript">
var createLinkObj;
$(function () {
$('#mydialog').dialog({
autoOpen: false,
width: 500,
modal: true,
buttons: {
"OK": function () {
$("#myForm").validate({
rules: {
Name: {
required: true
},
Email: {
required: true,
email: true
}
},
messages: {
Name: " * ",
Email: {
required: " * ",
email: " Invalid e-mail."
}
});
$("#myForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".mylink").click(function () {
//change the title of the dialog
createLinkObj = $(this);
var dialogDiv = $('#mydialog');
var viewUrl = createLinkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
dialogDiv.dialog('open');
});
return false;
});
});
</script>
As you can see when I click the mylink, mydialog appears and before submitting the myForm, I validated the myForm elements namely Name and Email.
Think that your form only contains Name and Email and then you can validate these elments by using jquery validate script.