I'm making a mobile website, using jQuery Mobile and ASP.NET 4.0 Webforms. I have made an initial login page (Default.aspx) in which the button calls an ajax JavaScript function, which calls a page method in the backend like so:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UCP.Default" %>
<!DOCTYPE html>
<html>
<head>
<title>UA Cover Plus</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
</head>
<body>
<!-- Login -->
<div data-role="page" id="login">
<div data-role="header" data-position="fixed">
<h1>Login</h1>
<a href="#Family" data-icon="gear" class="ui-btn-right" data-iconpos="notext" data-theme="b" >Options</a>
</div>
<div data-role="content" data-theme="a">
<input type="text" id="txtUserName" placeholder="Username" />
<input type="password" name="passwordinput" id="txtPassword" placeholder="Password" value="" />
Log Me In!
</div><!-- /content -->
</div><!-- /page -->
</body>
Ajax JQuery Function :
function Authenticate() {
$.ajax({
type: "POST",
url: "Default.aspx/Authenticate",
data: "{'name': '" + $('#txtUserName').val() + "','pass': '" + $('#txtPassword').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '-1') {
userId = msg.d;
GetCustomisedConsole();
} else {
alert("Authentication Failed");
}
},
error: function () {
alert("Error :(");
}
});
};
Page method in Default.aspx.cs
[WebMethod]
public static int Authenticate(string name, string pass)
{
using (DbContext db = new DbContext())
{
var user = db.Users.Where(x => x.UserName == name && x.Password == pass).SingleOrDefault();
if (user != null)
{
return user.Id;
}
else
{
return -1;
}
}
}
My question is, is this the way its meant to be done? I ask this because I see in the jQuery examples the use of forms and submits, which I have no idea how to implement in asp.net.
I'm doing in the same way and works perfect.
Please take a look to this example
Invoking Server Methods Using Jquery
Related
Am trying to create a CRUD operation using phonegap/cordova, and I keep receiving "Uncaught DOMException: An attempt was made to break through the security policy of the user agent. at window.onload - Line 17" pointing to =>"db = window.openDatabase("employee", "1.1", "LearnToProgram", 200000);". This further affects db.transaction Line 25 “Uncaught TypeError: Cannot read property 'transaction' of undefined”, because Database was not created. Do I need any SQLLite plugin on maybe there is something else missing?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>SQLLite DB App</title>
<script type="text/javascript" src="cordova.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
var db;
window.onload=function()
{
document.getElementById('btnSave').addEventListener('click', saveData);
db = window.openDatabase("employees", "1.0", "LearnToProgram", 200000);
}
function saveData(e)
{
db.transaction(saveRecord, onSuccess, onError);
}
function saveRecord(transaction)
{
var name= document.getElementById('name').value;
var email = document.getElementById('email').value;
transaction.executeSql('CREATE TABLE IF NOT EXISTS employeesList (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Email TEXT NOT NULL) ');
var sql= "INSERT INTO employeesList (Name,Email) VALUES ('" + name +"', '" + email + "')";
console.log(sql);
transaction.executeSql(sql);
}
function onSuccess()
{
console.log("Record Saved");
}
function onError(error)
{
console.log("SQL error: " + error.code);
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header"><h1>Database Storage</h1></div>
<div data-role="main" class="ui-content">
<label for="name">Name</label>
<input type="text" id="name" />
<label for="email">Email</label>
<input type="text" id="email" />
<button id="btnSave" type="submit">Save</button>
<button id="showList">Show Employees</button>
</div><!-- main-->
</div><!-- page -->
</body>
</html>
maybe I help you.
To open a database:
var db = null;
document.addEventListener('deviceready', function() {
db = window.sqlitePlugin.openDatabase({
name: 'my.db',
location: 'default',
});
});
IMPORTANT: Like with the other Cordova/phonegap plugins your application must wait for the deviceready event. This is especially tricky in Angular/ngCordova/Ionic controller/factory/service callbacks which may be triggered before the deviceready event is fired.
I want to make an client Windows Application using java script by make my Windows Application as webBrowser1 (same idea of PhoneGap). I write html page that contains SignalR javascript code with necessary src.
This is the code in Windows Application:
webBrowser1.Url = new Uri(#"D:\Signal.html");
This is the src in Signal.html:
<script src="json2.js"></script>
<script src="jquery-1.6.4.js"></script>
<script src="jquery.signalR-2.2.0.js"></script>
<script src="http://localhost:5539/signalr/hubs" type="text/javascript"></script>
Unfortunately it doesn't work!! What is the wrong??
The hole Code of SignalR.html is here
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="message" placeholder="Message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion"></ul>
</div>
<div style="background-color:GrayText; height:30%; text-align:center; ">
<h1>Groups</h1>
<input type="text" id="name" placeholder="User Name" />
<input type="text" id="groupName" placeholder="Group Name"/>
<input type="button" id="broadcast" value="Broadcast" />
<input type="button" id="join" value="Join" />
<input type="button" id="leave" value="Leave" />
<input type="button" id="refresh" value="Leave" />
</div>
<script src="json2.js"></script>
<script src="jquery-1.6.4.js"></script>
<script src="jquery.signalR-2.2.0.js"></script>
<script src="http://localhost:5539/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:5539/signalr";
// Declare a proxy to reference the hub.
var chat = $.connection.chatingHub;
var counterh = $.connection.ConnectionCounter;
//counterh.client.NumberOfConnter = function (count) { $("div").append(count); }
chat.client.displayText = function (name, message) {
$('#messages').append('<li>' + name + ' said: ' + message + '</li>');
};
chat.client.le = function (id) { alert(id); }
chat.client.alertJoin = function (namePersonJoined) { $('#messages').append('<li>' + namePersonJoined + " Join to the Group" + '</li>').css("background-color", "white"); }
chat.client.alertLeave = function (namePersonLeaved) { $('#messages').append('<li>' + namePersonLeaved + " Leave from the Group" + '</li>'); }
// Create a function that the hub can call to broadcast messages.
chat.client.addMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
$("#broadcast").click(function () {
chat.server.broadcastMessage({
Name: $('#name').val(),
Message: $('#message').val(), Group: $('#groupName').val()
});
});
$("#join").click(function () {
chat.server.join($('#groupName').val(), $('#name').val());
});
$("#leave").click(function () {
chat.server.leave($('#groupName').val(), $('#name').val());
});
$("#refresh").click(function () {
chat.server.nowID();
});
});
});
</script>
</body>
</html>
I think it's a CORS problem.
Your signalR client is in D:\SignalR.html
Your signalR server is in http://localhost:5539/signalr/hubs
meaning that it is a Cross Origin signalR calls. You need to enable CORS in order to let it works.
Telerik's TreeView control, although fancy and with a lot of functionality is proving to be a nightmare for me now. However I could not find a better TreeView control which supports collapsing/expanding etc. and has a little bit of documentation. Here's my problem.
This is the site master : _Layout.cshtml
<!DOCTYPE HTML>
<html>
<head>
<title>#ViewBag.Title</title>
<!--
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/custom.css")" rel="stylesheet" type="text/css" />-->
#(Html.Telerik().StyleSheetRegistrar()
.DefaultGroup(group =>
group.Add("telerik.common.css")
.Add("~/Content/Site.css")
.Add("~/Content/custom.css")
.Add("~/Content/themes/humanity/jquery-ui-1.8.18.custom.css")
.Combined(true)
.Compress(true)))
</head>
<body>
<div class="page">
<header>
<div id="header-logo">
<img alt="X" src="../../Content/Images/logo100.png"/>
</div>
<div id="title">
<h1>title</h1>
</div>
#(Html.Telerik().Menu()
.Name("menu")
.Items(menu =>
{
menu.Add().Text("Home").Action("Index", "Home");
menu.Add().Text("Products")
.Items(item =>
{
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
item.Add().Text("xxx").Action("xxx", "Products");
});
menu.Add().Text("Events").Action("Index", "Events");
menu.Add().Text("About Us").Action("About", "Home");
menu.Add().Text("Admin").Action("Index", "Admin");
})
.HtmlAttributes(new { style = "text-align:left;" }))
</header>
<section id="main">
#RenderBody()
</section>
<footer>
</footer>
</div>
#(Html.Telerik().ScriptRegistrar()
.Scripts(script=>script.Add("~/Scripts/custom.js"))
.Globalization(true)
.DefaultGroup(group => group.Combined(true)
.Compress(true)))
</body>
</html>
This is the base page view : Index.cshtml
#{
ViewBag.Title = "Admin";
}
<h2>
Admin Index</h2>
<div id="navAdminLeft">
#(Html.Telerik().TreeView()
.Name("AdminNavTree")
.Items(item =>
{
item.Add().Text("Products");
item.Add().Text("Categories");
item.Add().Text("Materials");
item.Add().Text("Finishes");
item.Add().Text("Packaging");
item.Add().Text("File Manager");
item.Add().Text("CategoryTree");
})
.ClientEvents(events => events.OnSelect("loadAdminContent"))
)
</div>
<div id="adminContent">
</div>
<script type="text/javascript">
function loadAdminContent(e) {
$.ajax({
type: "GET",
cache: false,
url: "Admin/" + e.item.innerText,
data: {},
success: function (data) {
$("#adminContent").html(data);
}
});
}
</script>
whenever the user selects a node on the #AdminNavTree the page fetches the content to be displayed and populates #adminContent. I am trying to build an edit page where there is a category tree listed in one div and when the user clicks on any of the category on that div, the details are ajax loaded into another div on the same page. Here is the partial view with the category tree that gets loaded into #adminContent: _CategoryTree.cshtml
#using xxx.Models.Navigation
#model IEnumerable<NavigationItem>
<div id="categoryTree">
#{Html.Telerik().TreeView()
.Name("ctree")
.BindTo(Model, mappings =>
mappings.For<NavigationItem>(binding => binding
.ItemDataBound((currentItem, navigationItem) =>
{
currentItem.Text = navigationItem.Text;
currentItem.Expanded = true;
})
.Children(child => child.Items)
))
.ClientEvents(events=>events.OnSelect("loadContent"))
.Render();
}
</div>
<div id="detail"></div>
<script type="text/javascript">
function loadCategoryDetail(e) {
$.ajax({
type: "POST",
url: "Admin/CategoryDetails",
data: { id: $("#ctree").data("tTreeView").getItemText(e.item) },
success: function (data) {
$("#detail").html(data);
}
});
}
</script>
the detail page that is ajax loaded does not contain any telerik controls so listing code for that is a non issue.
The PROBLEM : this will not render. As soon as it tries rendering #ctree treeview it starts throwing all kind of script errors, specifically it ignores loadCategories (says not found). So far I think what is happening is the ajax loaded partial page that contains the treeview is reloading the jquery lib destroying all old bindings and functions in the script. Is there a way to make this work, two treeviews on one page, one previously loaded, one in a ajax loaded partial view, both binding to separate data?
I've had good success with jsTree... doesn't help with your telerik question, but might be worth checking out.
http://www.jstree.com/
After upgrading my project from ASP.NET MVC2 to MVC3, simply calendar partial view no longer renders. The code for this view is listed below.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AkwiMemorial.Models.CalendarModel>" %>
<link href="../../Content/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.ui.datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#datepicker').datepicker({
inline: true,
onSelect: function(dateText, inst) {
$('#DateStr').val(dateText);
$('form').trigger('submit'); }});
});
</script>
<% using (Html.BeginForm()) { %>
<div>
<div id="datepicker"></div>
<%= Html.HiddenFor(x => x.DateStr)%>
</div>
<% } %>
Any ideas? TIA.
Edit 1:
To see if this is a problem with my original project, I modified Home/Index view on a new MVC3 project as shown below. When I execute, I get error "Microsoft JScript runtime error: Object doesn't support this property or method". This is using jquery-1.5.1.min.js.
#model DateTime
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('.date').datepicker({ dateFormat: "dd/mm/yy" });
});
</script>
#using ( Html.BeginForm())
{
#Html.TextBox("datepicker", Model.ToString("dd/MM/yyyy"), new { #class = "date" });
<input id="submit" name="submit" type="submit" value="Save" />
}
Why is this not working?
** Edit 2: **
Got jquery calendar to display in MVC3 using the following partial view:
#model DateTime
#using (Html.BeginForm())
{
<div id="datepicker">
#Html.TextBox("date", Model.ToString("dd/MM/yyyy"), new { #class = "date" })
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('#datepicker').datepicker({
inline: true,
onSelect: function (dateText, inst) {
$('#date').val(dateText);
$('form').trigger('submit');
}
});
});
</script>
Now back to the original problem.
I had the same problem and it fixed by upgrading to the latest version of jquery UI and jquery.
Without more info, my guess is that problem is with the nested div's. The default css of the browser could be playing a part here. Trying setting z-index of the datepicker div to a higher value.
Hi how can I pass a client side (JS) value in server side (C#)?
e.g.
I have a generated table (after uploading images) and it contains images and I want to select the image and throw the ID back in server side.
The uploade I used was JQuery Uploadify and I have a "onComplete" function
(simple code)
'onComplete': function (event, queueID, fileObj, response, data) {
$('#imgs').append('<img id="' + queueID + '" src="' + response + '" alt="' + response + '" />');
How can I do this?
To send a value from javascript to the server you have a couple of options:
Use AJAX if you want to stay on the current page
Redirect to a server side script and pass the value in the querystring
Let's consider the first case:
Assuming you have a web method capable of receiving the value on the server:
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true" %>
<script type="text/C#" runat="server">
// Server side script in the code behind that will receive
// the value: The method needs to be static
// and decorated with the WebMethod attribute
[System.Web.Services.WebMethod]
public static string Foo(string id)
{
return "ok";
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
// Send an AJAX request to the server
$.ajax({
url: '/default.aspx/foo',
type: 'POST',
contentType: 'application/json; charset=utf-8',
// Pass the value as JSON string
// You might need to include json2.js for the JSON.stringify
// method: http://www.json.org/json2.js
data: JSON.stringify({ id: 'someId123' }),
success: function (result) {
// The result is also JSON
alert(result.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>
are you using Asp.net Forms? If so, you do understand the concept of Page Lifecycle and how it affects the state of the page?
I would suggest going javascript all the way in this one, please see jQuery + AJAX.