Inserting data using ado.net via ajax - asp.net

i am having trouble in finding the problem. I was inserting product record via ado.net and it worked fine. Now i tried ajax for doing it in a more better way . but i am having trouble since the code never runs the function intended to run when i click button via ajax. so need ur help. Thanks. here is the code:
//this is my home.aspx page
$(document).ready(function () {
$("#submit").click(function () {
alert("you clicked");
$.ajax({
type: "POST",
contentType: "application/json",
url: "home.aspx/insert",
dataType: "json",
// data: "{'Name':'" + document.getElementById('name').value + "'}",
data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
</script>
//////////////////////////////////
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><label>Product Name</label></td>
<td> <asp:TextBox runat="server" id="name"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Code</label></td>
<td><asp:TextBox runat="server" id="code"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Category</label></td>
<td><asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Gadgets</asp:ListItem>
<asp:ListItem>Vehicles</asp:ListItem>
<asp:ListItem>Garments</asp:ListItem>
<asp:ListItem>Eatables</asp:ListItem>
<asp:ListItem>Furniture</asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td><label>Expiry date</label></td>
<td><asp:TextBox runat="server" TextMode="Date" id="dt"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product price</label></td>
<td><asp:TextBox runat="server" id="price"></asp:TextBox></td>
</tr>
<tr>
<td><label>Product Image</label></td>
<td> <asp:FileUpload ID="file_image" runat="server" /></td>
<td> </td>
<td><asp:Label runat="server" id="showtext"></asp:Label></td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td></td>
<%--<asp:Button runat="server" OnClick="submit" Text="Submit" BackColor="White" Width="100px" />--%>
<td> <input type="button" style=" width:100px;" value="Submit" id="submit" /> </td>
</tr>
</table>
</div>
<asp:Label ID="res" runat="server"></asp:Label>
</form>
///////////////////////////////////////////////
//this is my home.aspx.cs page :
public void insert()
{
if (file_image.HasFile)
{
string ext = System.IO.Path.GetExtension(file_image.FileName);
if (!ext.Equals(".jpg"))
{
showtext.Text = "Please select correct file format i.e jpg or jpeg";
showtext.ForeColor = System.Drawing.Color.Purple;
}
else
{
file_image.SaveAs(Server.MapPath("~/Uploads/" + file_image.FileName));
showtext.Text = "File uploaded";
showtext.ForeColor = System.Drawing.Color.Green;
productclass pc = new productclass();
pc.Pr_name = name.Text;
pc.Code = code.Text;
pc.Category = DropDownList1.SelectedValue;
pc.Expiry = Convert.ToDateTime(dt.Text);
pc.Price = Convert.ToInt32(price.Text);
pc.Pr_image = file_image.FileName;
dalinsert di = new dalinsert();
bool flag = di.insert(pc);
if (flag.Equals(true))
{
res.Text = "data inserted";
//Thread.Sleep(10000);
// Response.Redirect("home.aspx");
}
else
{
res.Text = "issue in inserting data";
}
}
}
else
{
showtext.Text = "Please select file";
showtext.ForeColor = System.Drawing.Color.Red;
}
}

Related

how to get label id in asp.net for using in jquery,?

I am not getting label id in jquery code , i use anchor tag , it is working , the text changes to today's date on page load , but when i apply it to label control of asp.net , it doesn't work , search may pages on web , but doesn't get proper solution how to change text of label using java script or jquery , is here anybody can solve it.
here is the code to look out .
<div>
<div>
<table class="foruploadtable">
<tr>
<td>
<span class="foruploadtabletitle" >Share From Here .</span>
<hr />
</td>
</tr>
<tr>
<td>Max Size 1MB :</td><td>
<asp:FileUpload ID="FileUpload1" ToolTip="Select File By Clicking Browse ." CssClass="foruploadtableupload" runat="server" /></td>
</tr>
<tr>
<td>
<asp:Button ID="b1" runat="server" CssClass="foruploadtablebutton" ToolTip="Click Here To Upload." Text="Upload." OnClick="b1_Click" />
</td>
<td>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<a id="me">hello</a>
</td>
</tr>
</table>
</div>
</div>
<script>
$(document).ready(function () {
var say = $('#me').text();
var date = new Date();
$('#me').text(date.getDate());
$('#Label1').text(date.getDate());
// alert(date.getDate());
});
</script>
Try this:
change label add attribute ClientIDMode="Static"
<asp:Label ClientIDMode="Static" ID="Label1" runat="server" Text="Label"></asp:Label>
$('#Label1').text(date.getDate());
or
$('#<%= Label1.ClientID %>').text(date.getDate());
You can try this.
$(document).ready(function () {
var say = $('#me').text();
var date = new Date();
$('#me').text(date.getDate());
$('#<%= Label1.ClientID %>').text(date.getDate());
// alert(date.getDate());
});
Make sure that your page does not have master page. If it is so then you can use Client ID as below
<script>
$(document).ready(function () {
var say = $('#me').text();
var date = new Date();
$('#me').text(date.getDate());
$('#<%=Label1.ClientID%>').text(date.getDate());
// alert(date.getDate());
});
You can try this,
$('#<%=Label1.ClientID%>').text(date.getDate());
This helps to grab the id generated by ASP.Net for the id parameter..

binding data through jquery to table

I am using load on page scroll . from this link
http://aspsnippets.com/Articles/Load-data-while-Scrolling-Page-down-with-jQuery-AJAX-and-ASPNet.aspx
On page load it display's 10 record in form of table, I am binding unique id to table from database. Starting 10 row's bind id correctly , but after 10th row I see {source code}, Id on all table after 10th is same it's taking id on first table. I am using this table unique id for removing table when delete is done.
I am also using a usercontrol inside this table. Usercontrol is behaving in the same way as table. After 10th row usercontrol repets id of first table. Here's my code.
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: 'CS.aspx/GetCustomers',
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var customers = xml.find("Customers");
customers.each(function () {
var customer = $(this);
var table = $("#dvCustomers table").eq(0).clone(true);
$(".name", table).html(customer.find("Title").text());
$(".city", table).html(customer.find("Description").text());
$(".postal", table).html(customer.find("UserID").text());
$(".country", table).html(customer.find("EmailID").text());
$(".phone", table).html(customer.find("Status").text());
$(".fax", table).html(customer.find("UserID").text());
$(".MainCommentscont", table).html(customer.find("ID").text());
$(".MainComments", table).html(customer.find("ID").text());
$("#dvCustomers").append(table).append("<br />");
});
$("#loader").hide();
}
</script>
I want this ID should bind with table(inside repeter) and usercontrol and should not repeat after 10th row.
<form id="form1" runat="server">
<table>
<tr>
<td>
<div id="dvCustomers">
<asp:Repeater ID="rptCustomers" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
border: dashed 2px #04AFEF; background-color: #B0E2F5" class="MainCommentscont" id='<%# Eval("ID")%>'>>
<tr>
<td>
<b><u><span class="name">
<%# Eval("Status")%></span></u></b>
</td>
<td>
<b>Desc: </b><span class="MainComments">
<%# Eval("ID")%></span><br />
<b>Desc: </b><span class="city">
<%# Eval("Description")%></span><br />
<b>User: </b><span class="postal">
<%# Eval("UserID")%></span><br />
<b>Email: </b><span class="country">
<%# Eval("EmailID")%></span><br />
<b>point: </b><span class="phone">
<%# Eval("Status")%></span><br />
<b>Fax: </b><span class="fax">
<%# Eval("UserID")%></span><br />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
</td>
<td valign="bottom">
<img id="loader" alt="" src="loading.gif" style="display: none" />
</td>
</tr>
</table>
</form>
I think problem, you don't change table ID after clone. Could you try that?
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var customers = xml.find("Customers");
customers.each(function () {
var customer = $(this);
var table = $("#dvCustomers table").eq(0).clone(true);
$(".name", table).html(customer.find("Title").text());
$(".city", table).html(customer.find("Description").text());
$(".postal", table).html(customer.find("UserID").text());
$(".country", table).html(customer.find("EmailID").text());
$(".phone", table).html(customer.find("Status").text());
$(".fax", table).html(customer.find("UserID").text());
$(".MainCommentscont", table).html(customer.find("ID").text());
$(".MainComments", table).html(customer.find("ID").text());
//Change table ID
$(table).attr('ID',customer.find("ID").text());
//-
$("#dvCustomers").append(table).append("<br />");
});
$("#loader").hide();
}

ASP.NET Enter key

I have a master page and based on that master page I created a page with a TextBox and two Validation controls for RequiredValidator and RegularExpressionValidator and one ValidationSummary.
when pressing the enter key in TextBox, I expected that both validator show their errorMessage on validationSummary but thats not what happening it only works when I press the button on page.
According to this page I wrapped my code with <asp:panel> and a DefaultButton attribute but it didn't solve the problem.
http://www.codeproject.com/KB/aspnet/aspnet_Enter_key_problem.aspx
I want to know what the problem here is and whether there is any workaround?
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
**<asp:Panel runat="server" DefaultButton="EmailSend">**
<table style="width: 100%">
<tr>
<asp:ValidationSummary ID="EmailValidation" runat="server" CssClass="failureNotification"
ValidationGroup="EmailValidation" />
</tr>
<tr>
<td style="width: 76px">
Email:
</td>
<td class="style1">
<asp:TextBox ID="EmailForget" runat="server" Width="244px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="EmailRequiered" runat="server" ControlToValidate="EmailForget"
CssClass="failureNotification" ErrorMessage="RequiredFieldValidator" ValidationGroup="EmailValidation">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="EmailRegular" runat="server" ControlToValidate="EmailForget"
CssClass="failureNotification" ErrorMessage="email required"
ValidationGroup="EmailValidation">*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td style="width: 76px">
</td>
<td class="style1">
<asp:Button ID="EmailSend" runat="server" Text="send" Width="56px" ClientIDMode="Static" />
</td>
<td>
</td>
</tr>
</table>
**<asp:Panel>**
</asp:Content>
Try adding this code
<script type="text/javascript">
if (document.addEventListener) {//if Firefox
document.addEventListener("keypress", fireFoxHandler, true);
} else {
document.attachEvent("onkeyup", ieHandler);
}
function fireFoxHandler(evt) {
if (evt.keyCode == 13) {
document.getElementById("EmailSend").click();
}
}
function ieHandler(evt) {
if (evt.keyCode == 13) {
document.getElementById("EmailSend").click();
}
}
</script>
Found this solution here.
(I didn't check this in MasterPage scenario, please check...)
If you are using IE then according to the answers on these two pages:
ASP.NET enter key and form submit with no javascript
Enter button does not submit form (IE ONLY) ASP.NET
you only need to add the following to your form
<!-- Fix for IE bug submit on pressing "Enter") -->
<div style="display:none">
<input type="text" name="hiddenText"/>
</div>
I solved this problem like this:
protected void Page_Load(object sender, EventArgs e)
{
textboxusername.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + LinkButton1.UniqueID + "','')");
textboxpassword.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + LinkButton1.UniqueID + "','')");
}
and this is the link..
<asp:LinkButton ID="LinkButton1" runat="server" class="btn" OnClick="LinkButton1_Click">

Facebook Javascript SDK share to facebook wall

I am getting an error: 'share' is not a member of 'ASP.default2_aspx'.
OnClick of Button1, I need this data TxtLocation, TxtDistance, Date to be shared on Facebook. Its very similar to 'Run with friends app' Simulate the same as Run with friends app'. So would it be possible to use a fb.ui stream_publish method on click of Button1 with all the three text box vales.
This is what I have in default.aspx
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt) {
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function (response) {
});
}
function share() {
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};
FB.ui(share, function (response) { console.log(response); });
}
</script>
<p><fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button></p>
<form id = "form1" runat="server">
<div id="Event" runat="server">
<h1>
Add your event</h1>
<table>
<tr>
<td>
Where did you go
</td>
<td>
<asp:TextBox ID="TxtLocation" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Number of miles
</td>
<td>
<asp:TextBox ID="TxtDistance" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Date(MM/DD/YYYY)
</td>
<td>
<asp:TextBox ID="TxtDate" runat="server">TxtDate</asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Button1" runat="server" Text="Add Distance" onclick="share();return false" BackColor="Blue" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Maybe it's because share is already the name of the function.
Try changing the name of the var inside the function share.
Bye ;)

ASP.Net JScript Error on Show Hide using IE8

I am getting the following javascript error when changing the value in the dropdownlist. The error only occurs when using IE8, it works fine in IE6 and IE7. The error is: 'value' is null or not an object
Here is the code.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<table cellpadding="3" cellspacing="1">
<tr>
<td style="text-align: right">* Who is reporting the issue:</td>
<td>
<asp:DropDownList ID="ddlWhoReportedIssue" runat="server"
CausesValidation="false">
<asp:ListItem></asp:ListItem>
<asp:ListItem>Self</asp:ListItem>
<asp:ListItem>Agent's Office</asp:ListItem>
<asp:ListItem>Other Employee In Dept.</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr id = "Row1" style="display:none">
<td style="text-align: right">* State Agent Code:</td>
<td>
<asp:TextBox ID="txtStateAgentCode" runat="server" Columns="20" MaxLength="50"></asp:TextBox>
</td>
</tr>
<tr id = "Row2" style="display:none">
<td style="text-align: right">* Name of Caller:</td>
<td>
<asp:TextBox ID="txtNameOfCaller" runat="server"></asp:TextBox>
</td>
</tr>
<tr id = "Row3" style="display:none">
<td style="text-align: right">* Name & Alias of Other Employee:</td>
<td>
<asp:TextBox ID="txtNameAndAlias" runat="server" Columns="30" MaxLength="50"></asp:TextBox>
</td>
</tr>
</table>
<script type="text/javascript">
function fcnShowHide1() {
if (aspnetForm.ctl00_ContentPlaceHolder2_ddlWhoReportedIssue.value == "Self") {
document.all.Row1.style.display = "none"
document.all.Row2.style.display = "none"
document.all.Row3.style.display = "none"
} else if (aspnetForm.ct100_ContentPlaceHolder2_ddlWhoReportedIssue.value == "Agent's Office") {
document.all.Row1.style.display = ""
document.all.Row2.style.display = ""
document.all.Row3.style.display = "none"
} else if (aspnetForm.ct100_ContentPlaceHolder2_ddlWhoReportedIssue.value == "Other Employee In Dept.") {
document.all.Row1.style.display = "none"
document.all.Row2.style.display = "none"
document.all.Row3.style.display = ""
}
}
</script>
</asp:Content>
Change the function to this:
function fcnShowHide1() {
var oDDL = document.getElementById("<%=ddlWhoReportedIssue.ClientID%>");
var sValue = oDDL.value;
if (sValue == "Self") {
document.getElementById("Row1").style.display = "none";
document.getElementById("Row2").style.display = "none";
document.getElementById("Row3").style.display = "none";
} else if (sValue == "Agent's Office") {
document.getElementById("Row1").style.display = "";
document.getElementById("Row2").style.display = "";
document.getElementById("Row3").style.display = "none";
} else if (sValue == "Other Employee In Dept.") {
document.getElementById("Row1").style.display = "none";
document.getElementById("Row2").style.display = "none";
document.getElementById("Row3").style.display = "";
}
}
Hard coding the dynamically generated ID is really bad idea - get the real ID using ClientID.
Plus document.all is even worse, use document.getElementById instead.

Resources