binding data through jquery to table - asp.net

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();
}

Related

Inserting data using ado.net via ajax

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;
}
}

How to validate dropdown in asp.net mvc2.0?

I am using asp.net mvc 2.0.I have to validate my dropdownlist after clicking save button.
this is my view code.
<%using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "Save" }))
{
%>
<table>
<tr>
<td>
<%:Html.TextBoxFor(m => m.EmployeeName)%>
</td>
</tr>
<tr>
<td>
<%:Html.DropDownListFor(m => m.ProjectModel, new SelectList(Model.ProjectModel, "Id", "ProjectName"), new { #id = "ddlProject"})%>
</td>
</tr>
<tr>
<td>
<input id="btnSave" type="button" value="Save" />
</td>
</tr>
</table>
<center>
<div id="result">
<%Html.RenderPartial("~/Views/PartialViews/partialpage.ascx");>
</div>
</center>
</table>
<%} %>
and my java script code is:
$(document).ready(
function () {
$('#btnSave').click(function () {
$.ajax(
{
cache: false,
async: true,
type: "POST",
url: $('#Save').attr('action'),
data: $('#Save').serialize(),
success: function (data) {
$('#result').html(data);
},
error: function (data) {
}
});
});
});
here am using
input type="button"
because i have to return partial view after submit save button.
can anyone tell how to validate my dropdown??
I write this as follow in Asp.Net Mvc4. I think that perhaps it is same in Mvc2.
#Html.DropDownListFor(model => model.Contract.ContractStatusId, new SelectList(Model.ContractStatus, "ContractStatusId", "Name"), "-- Select Status --", new { data_form = "select2", #style = "width: 200px;" })
#Html.ValidationMessageFor(model => model.Contract.ContractStatusId)

customize popup window in telerik grid in mvc

i have to display customize popup window in telerik grid because i cannot display all values in grid so i want when user click on grid edit button and according to particular row datakey
fetch data from table and display those records in popup window and i want to open that window when user click on grid button not on my checkout button so what can i do
view
<%# Page Title="" Language="C#" MasterPageFile="~/Content/JobSeekers.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<ITClassifieds.ViewModels.workexperience>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
trial
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function onRowSelected(e) {
var ordersGrid = $('#Grid').data('tGrid');
var resexpid = e.row.cells[0].innerHTML;
// update ui text
$('#rexsepid').text(resexpid);
// rebind the related grid
// ordersGrid.rebind({
// resexpid: resexpid
// });
var window = $("#Window").data("tWindow");
window.center().open();
}
function closeWindow() {
var window = $("#Window").data("tWindow");
window.close();
var undoButton = $('#undo');
undoButton.show();
}
function openWindow() {
var window = $("#Window").data("tWindow");
window.center().open();
// var ordersGrid = $('#Grid').data('tGrid');
// var resexpid = ordersGrid.row.cells[0].innerHTML;
// $('#rexsepid').text(resexpid);
// alert(resexpid);
}
function viewDetails(activityId) {
//....Do stuff here...
alert(activityId);
}
</script>
<h2>trial</h2>
<%=Html.Telerik().Grid(Model).Name("Grid").DataKeys(keys => keys.Add(m => m.resexpid))
.Columns(columns=>
{
columns.Bound(m => m.resexpid).Width(100);
columns.Bound(m => m.company).Width(100);
//columns.Bound("Title").Width(100);
columns.Bound(m=>m.title).Width(200);
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Text);
commands.Delete().ButtonType(GridButtonType.Text);
}).Width(200).Title("Command");
columns.Bound(m => m.resexpid).ClientTemplate("<a onclick='viewDetails('" + "'<#= Id #>'" + "');' href='javascript:'>View</a>").Title("View");
//columns.Bound(m => m.Date).Width(200);
})
.ClientEvents(events => events.OnRowSelect("onRowSelected"))
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_FirstLook","Editresume")
.Update("_SaveAjaxEditing", "Editresume")
.Delete("_DeleteAjaxEditing", "Editresume");
})
.Scrollable(scrolling => scrolling.Enabled((bool)ViewData["scrolling"]))
.Sortable(sorting => sorting.Enabled((bool)ViewData["sorting"]))
.Pageable(paging => paging.Enabled((bool)ViewData["paging"]))
.Filterable(filtering => filtering.Enabled((bool)ViewData["filtering"]))
.Groupable(grouping => grouping.Enabled((bool)ViewData["grouping"]))
.Footer((bool)ViewData["showFooter"])
.RowAction(row => row.Selected = row.DataItem.resexpid.Equals(ViewData["id"]))
%>
<button class="button medium gray" onclick="openWindow()">Checkout</button>
<% Html.Telerik().Window()
.Name("Window")
.Title("Update Option")
.Draggable(false)
.Resizable(resizing => resizing
.Enabled(true)
.MinHeight(250)
.MinWidth(250)
.MaxHeight(500)
.MaxWidth(500)
)
.Scrollable(true)
.Modal(true)
.Buttons(b => b.Maximize().Close())
.Content(() =>
{%>
<div>
<%-- <% %>
<% if (ResumePackgeExits == true && JobPackageExist == true)
{
}
else if (ResumePackgeExits == false && JobPackageExist == true)
{
%>--%>
<div>
<table border="1" cellpadding="5" cellspacing="0" bordercolor="#CCCCCC" style="font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;border:1px solid #AAA;margin:5px;">
<tr> <td colspan="3">
We Are also Provied a Unlimeted Resume Subscription.
if You Want a Resume Subscription Please click on RESUME Package button.
</td></tr>
</table>
<br />
<%=Html.ActionLink("RESUME Package", "ResumePackage", null, new { #class = "button medium gray" })%>
</div>
<%--<%}else if(ResumePackgeExits == true && JobPackageExist == false)
{%>
--%>
<div>
<table border="1" cellpadding="5" cellspacing="0" bordercolor="#CCCCCC" style="font-family:Verdana, Arial, Helvetica, sans-serif;font-size:11px;border:1px solid #AAA;margin:5px;">
<tr>
<td colspan="3">
We Are also Provied a Job Subscription.
if You Want a Job Subscription Please click on JOB Package button.
</td>
</tr>
</table>
<br />
<%=Html.ActionLink("JOB Package", "jobpackage", null, new { #class = "button medium gray" })%>
</div>
<%-- <%} %>--%>
<br />
<%-- <% using (Html.BeginForm("Checkout", "Package", FormMethod.Post, new { name = "frmDCC", onsubmit = "return CheckForm();" }))
{ %>
<input type="hidden" value="<%= Model.Total%>" name="totalPayment" />
<table>
<tr>
<td><%=Html.RadioButton("paymentoption","paypalPayment") %></td>
<td><img src='https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif' border='0' align='top' alt='Check out with PayPal' /></td>
</tr>
<tr>
<td><%=Html.RadioButton("paymentoption","CreditCart") %></td>
<td> <img src="https://www.paypal.com/en_US/i/bnr/horizontal_solution_PPeCheck.gif" border="0" alt="Check out with Credit Cart" /></td>
</tr>
</table>
<input type="submit" value="Go" name="submit" class="button medium gray" />
<%} %>
--%>
</div>
<%})
.Width(500)
.Height(400)
.Visible(false)
.Render();
%>
</asp:Content>
controller
public ActionResult trial()
{
//var re = (from j in db.Resumes
// select new
// Jobresults { JobTitle = j.JobTitle, Company = j.CompanyInfo }).AsEnumerable();
var re = (from j in db.Resumes join res in db.Res_Exp on j.ResumeID equals res.Resume.ResumeID
where j.ResumeID == 258
select new workexperience {title=j.ResumeTitle,company=j.DesiredCompany ,resexpid=res.ResExpID}
).AsEnumerable();
ViewData["ajax"] = true;
ViewData["scrolling"] = true;
ViewData["paging"] = true;
ViewData["filtering"] = true;
ViewData["grouping"] = true;
ViewData["sorting"] = true;
ViewData["showFooter"] = true;
return View(re);
}
In order to make customized popup in telerik grid you need to exploit editor templates. You will make an editor template for your viewmodel. this brad wilson's tutorial will help you to get start. this post at telerik forum may also help you also

ASP.NET MVC: How to call javascript function in Html.ActionLink

When I edit single recored in page, I use checkbox to get a selected row not every row with an actionlink element, but it seemed I cant make this way happen through calling javascript code (function GetSelectedRow() should return an id). Could anyone have a nice idea?
<head runat="server">
<title>Index</title>
<script type="text/javascript" language="javascript">
function GetSelectedRow() {
var a = 0;
var chkBoxes = document.getElementsByName("chkSelect");
var count = chkBoxes.length;
for (var i = 0; i < count; i++) {
if (chkBoxes[i].checked == true)
a = chkBoxes[i].primaryKeyID;
}
return a;
}
</script>
</head>
<body>
<div>
<span style="width:20%">
<%: Html.ActionLink("Add", "Create")%>
</span>
<span>
<%: Html.ActionLink("Edit", "Edit", new { id = GetSelectedRow()) %>
</span>
<span>
<%: Html.ActionLink("Detial", "Details", new { id = GetSelectedRow() })%>
</span>
<span>
<%: Html.ActionLink("Delete", "Delete", new { id = GetSelectedRow()) %>
</span>
</div>
<table>
<tr>
<th></th>
<th>
CategoryID
</th>
<th>
CategoryName
</th>
<th>
Description
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Details", "Details", new { id = item.AppCategoryID })%>
</td>
<td>
<%: Html.CheckBox("chkSelect", false, new { primaryKeyID = item.AppCategoryID })%>
</td>
<td>
<%: item.AppCategoryID %>
</td>
<td>
<%: item.AppCategoryName %>
</td>
<td>
<%: item.Description %>
</td>
</tr>
<% } %>
</table>
</body>
You could do something like this:
<script type="text/javascript">
function RedirectUsingSelectedRow() {
var id = GetSelectedRow();
window.location = '../Controller/Details/' + id;
}
</script>
Edit
Mixing server and client that way won't work. What you need to do, when a row is selected, is to manipulate the URL. So rather than return a URL, have GetSelectedRow do:
function GetSelectedRow() {
//existing logic minus return
var link1 = document.getElementById("Link1"); //this would require giving links an ID
link1.href = '<%= Url.Action("Detail", new { controller = "Details" }) %>' +
'id=' a.toString();
}
You have to change it from client-side javascript is the key, rather than doing that during the rendering process.
HTH.
Try this -
$('#GetSelectedRow').click(function() { /* Your Code */ });
Calling java script function by id 'GetSelectedRow'. Instead of calling the function by id, you can directly call the function
<% Html.ActionLink("Edit", "Edit", "Controller", new { onclick = "GetSelectedRow();"}) %>

How to change this code in to $.ajax so that I can display message after saving to the database?

I am using this ccode right now..
<%using (Html.BeginForm("SaveNewServiceTypeCategory","ServiceTypeCategory")){ %>
<table>
<tr>
<td>Service type category:</td>
<td style="padding-left:5px;">
<input type="text" id="txtNewServiceTypeCategory" name="txtNewServiceTypeCategory" style="width:400px;" maxlength="30" />
</td>
</tr>
<tr>
<td valign="top">Service type description:</td>
<td style="padding-left:5px;">
<textarea id="txtNewServiceTypeCategoryDesc" name="txtNewServiceTypeCategoryDesc" style="width:400px;" rows="3"></textarea>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save"/>
</td>
</tr>
</table>
<%} %>
But I need to display the Popup message when data added to the Database..
I wrote somethign like this
$(function () {
$('#form1').submit(function () {
$.ajax({
url: , how to give the URl here?
type: this.method,
data: $(this).serialize(),
success: function () {
alert("Saved Successfully!");
}
});
return false;
});
After saving need to display saved Successfully message to the User?
thanks
});
You could start by giving your form an unique id:
<% using (Html.BeginForm(
"SaveNewServiceTypeCategory",
"ServiceTypeCategory",
FormMethod.Post,
new { id = "form1" })) { %>
And then use this id to register for the submit event:
$(function () {
$('#form1').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert('Saved Successfully!');
}
});
return false;
});
});
There's also the jquery form plugin which allows you to AJAXify an existing form very easily:
$(function () {
$('#form1').ajaxForm(function() {
alert('Saved Successfully!');
});
});

Resources