Access Function From aspx page - asp.net

public void storescore()
{
ScoreBAL bal = new ScoreBAL();
ScoreBOL bol = new ScoreBOL();
bol.userid = uid;
bol.time =lbltime.Text;
bol.scores = lblmark.Text;
bol.dates = DateTime.Now;
bal.insertscore(bol);
}
I have a function in code behind.I want to call the function written in c# code behind.Please send the code to access it using Jquery...

You cannot call any function written in your code behind in javascript.
You can only call static webmethods.
aspx:
<asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
<script type="text/javascript">
function StoreScore() {
PageMethods.storescore();
}
</script>
cs:
[System.Web.Services.WebMethod]
public static void storescore()
{
ScoreBAL bal = new ScoreBAL();
ScoreBOL bol = new ScoreBOL();
bol.userid = uid;
bol.time =lbltime.Text;
bol.scores = lblmark.Text;
bol.dates = DateTime.Now;
bal.insertscore(bol);
}

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "/PageName/storescore",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
},
error: function (msg) {
alert(msg);
}
});
</script>
code behind:
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
[WebMethod]
public static void StoreScore()
{
//do something
}

Related

Make ASP.NET AJAX function call synchronous

I have an ASP.NET form that calls a web service using ASP.NET AJAX. How do I make the call synchronous?
// test.aspx
<script type="text/javascript">
function GetDescription(){
var code = document.getElementById("<%=txtCode.ClientID%>").value;
var description =
MyNamespace.MyService.GetDescription(
code, onSuccessGetDescription, null, null);
return false;
}
function OnSuccessGetDescription(result){
var txtDescription =
document.getElementById("<%=txtDescription.ClientID%>");
}
</script>
<script type="text/javascript">
$(document).ready(//function () {
$('#<%=cmdSave.ClientID%>').click(function (e) {
e.preventDefault();
if (Page_ClientValidate()){
// Populate jQuery.UI dialog box with code and description
// and then
$("#confirm-dialog").dialog("open");
}
});
}
</script>
<asp:TextBox ID="txtCode" />
<asp:TextBox ID="txtDescription" />
<asp:Button ID="cmdSave" />
// test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
txtCode.Attributes["onblur"] = "GetDescription();";
}
The answers to this question that I have seen say that I should set the async attribute to false, but I don't see how to do that here.
ASP.Net Ajax - PageMethods Synchronous call and retrieval of results says that it can't be done. I am trying to get a second opinion.
If I can't make the call synchronous, would it be legal to make GetTransaction poll until the OnSuccess function returns? What would be an efficient (i.e. not CPU-intensive) way to do that?
JQuery Asynchronous
jQuery.ajax({
url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
success: function (result) {
if (result.isOk == false) alert(result.message);
},
async: false
});

ajax call not posting json data in asp.net

Iam trying to send some JSON data to the server using jquery ajax call. It doesn't seem like the data is posting as when i try to parse it in the code-behind file it throws errors. Searched around but the answers didn't help solve my problem. Any guidance would be appreciated.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
$.ajax({
url: 'Default2.aspx',
type: 'post',
async: false,
contentType: 'application/json; charset=utf-8',
//data: "'"+batchtable+"'",
data: JSON.stringify({"a":"1", "b": "2"}),
dataType: 'json',
processData: false,
success: function (result) {
alert('success');
},
error: function (result) {
alert('failed');
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
And here is the .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;
using System.Web.Script.Serialization;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var jsonString = String.Empty;
HttpContext context = HttpContext.Current;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
RootObject userinput = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(jsonString);
}
}
public class RootObject
{
public string a { get; set; }
public string b { get; set; }
}
The error message I get is:
Invalid JSON primitive: __VIEWSTATE.
for ajax call don't call from server side event.you need to call from javascript/jquery.
you need to define a serverside webmethod and you can call that method from the jquery/javascript. here is a demo. works fine. might be helpful for you.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnResult").click(function () {
var name = $("#txtNameTextBox").val();
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{name:'" + name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(data.d);
$("#Result").text(data.d);
var val = data.d;
val = val.split("~");
var name = val[0];
var time = val[1];
var date = val[2];
var tempdate = date.split(":");
var finaldate = tempdate[1];
$("#txtDateToDisplay").val(finaldate);
$("#txtDateToDisplay2").val(finaldate);
},
error: function () { alert(arguments[2]); }
});
});
});
</script>
here is HTML
<h2>
Call Server side Function From JaxaScript AJAX Call ASP.NET!
</h2>
<br />
<br />
<div>
Name : <input type="text" id="txtNameTextBox" /><br/><br/>
Date : <input type="text" id="txtDateToDisplay" /><br/><br/>
Date : <input type="text" id="txtDateToDisplay2" />
<br />
<br />
<p id="Result">Message : </p>
<input type="button" id="btnResult" value="Click here for the time"/>
</div>
And here your server side code
/// <summary>
/// ===========================================
/// This is the WebMethod where ajax call happens.
//=============================================
/// </summary>
/// <param name="name">the data sent from ajax call
/// - here a string only(name of a user)</param>
/// <returns>a string with json format</returns>
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetDate(string name)
{
if (name == "")
{
return "No Parcel Available";
}
else
{
name = "Name : " + name + "~" +
"Current Time : " + DateTime.Now.ToLongTimeString()
+ "~" + "Date : " + DateTime.Now.ToShortDateString();
}
return name;
}
Hope it will help you.
You need to use JavaScript/jQuery to call a server-side endpoint. ASP.NET AJAX Page Methods provide web methods that are hosted inside of a page, but are static and are not part of the page instance, so you can call them asynchronously via your client-side script, like this:
Markup:
<div id="Results"></div>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "YourPage.aspx/GetGreeting",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Put greeting into DIV
$('#Results').text(result.d);
}
});
});
Code-behind:
[WebMethod]
public static string GetGreeting()
{
return "Hello world!";
}
Note: The above example uses the client (via jQuery) to ask the server for a greeting (string), which is JSON-encoded automatically by the ASP.NET AJAX Page Method. The result is then processed by the success handler of the jQuery .ajax() function and the actual string value is pulled out of the .d reference in the returned JSON object.

Twitter TypeAhead with Asp .Net

Hi All can anyone provide me a good example of how to use Twitter Typeahead (http://twitter.github.io/typeahead.js/) in asp .net with database.
Thanks
In ASP.NET MVC you can create a controller action that returns JSON, like this:
view
#Html.TextBox("playerName")
<script type="text/javascript">
$(function () {
$('#playerName').typeahead({
name: 'players',
valueKey: 'playerName'
prefetch: '#Url.Action("AvaliablePlayers", "Player")',
limit: 10
});
});
</script>
controller and action
public class PlayerController : Controller
{
public JsonResult AvaliablePlayers(int groupId)
{
var group = _groupRepository.GetById(groupId);
return Json(group.Players.Select(p => new { playerId = p.PlayerID, playerName = p.Name), JsonRequestBehavior.AllowGet);
}
}
And in ASP.NET WebForms you can use custom HTTP handler to return data in JSON format, like this:
Default.aspx
<asp:TextBox id="country" CssClass="countryTypeAhead" runat="server"></asp:TextBox>
<script type="text/javascript">
$(function () {
$('.countryTypeAhead').typeahead({
name: 'countries',
prefetch: '<%= Page.ResolveClientUrl("~/Countries.ashx") %>',
limit: 10
});
});
</script>
Add new Generic Handler (.ashx) named Countries to your project. Here is the Code-behind for the handler:
public class Countries : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var cntries = new List<string>() {"Slovenia", "Italy", "Germany", "Austria"};
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
context.Response.Write(jsSerializer.Serialize(cntries));
}
public bool IsReusable
{
get
{
return false;
}
}
}
This sample uses JavaScriptSerializer which is available in ASP.NET 3.5 and above. If you are using asp.net of lover version than 3.5 you can use JSON.NET to convert typeahead results to JSON format.

Load ascx via jQuery

Is there a way to load ascx file by jQuery?
UPDATE:
thanks to #Emmett and #Yads. I'm using a handler with the following jQuery ajax code:
jQuery.ajax({
type: "POST", //GET
url: "Foo.ashx",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
jQuery('#controlload').append(response.d); // or response
},
error: function ()
{
jQuery('#controlload').append('error');
}
});
but I get an error. Is my code wrong?
Another Update :
I am using
error: function (xhr, ajaxOptions, thrownError)
{
jQuery('#controlload').append(thrownError);
}
and this is what i get :
Invalid JSON:
Test =>(this test is label inside my ascx)
and my ascx file after Error!!!
Another Update :
my ascx file is somthing like this:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server">Test</asp:Label>
but when calling ajax i get this error in asp: :(
Control 'ctl00_ddl' of type 'DropDownList' must be placed inside a form tag with runat=server.
thanks to #Yads. but his solution only work with html tag.
Building off Emmett's solution
public class FooHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write(RenderPartialToString("Foo.ascx"));
}
private string RenderPartialToString(string controlName)
{
Page page = new Page();
Control control = page.LoadControl(controlName);
page.Controls.Add(control);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Use the following jquery request
jQuery.ajax({
type: "POST", //GET
url: "Foo.ashx",
dataType: "html",
success: function (response)
{
jQuery('#controlload').append(response); // or response
},
error: function ()
{
jQuery('#controlload').append('error');
}
});
public ActionResult Foo()
{
return new ContentResult
{
Content = RenderPartialToString("Foo.ascx", null),
ContentType = "text/html"
};
}
//http://www.klopfenstein.net/lorenz.aspx/render-partial-view-to-string-asp-net-mvc-benchmark
public static string RenderPartialToString(string controlName, ViewDataDictionary viewData)
{
ViewPage vp = new ViewPage();
vp.ViewData = viewData;
Control control = vp.LoadControl(controlName);
vp.Controls.Add(control);
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
vp.RenderControl(tw);
}
}
return sb.ToString();
}
*.ascx files are rendered on the server side (inside of an *.aspx page), not the client side (where JavaScript is executed).
One option might be to create a blank *.aspx, put the user control on the *.aspx page, and then get that page via jQuery and dump the result on the page.
Edit
Based on your comment, I have another suggestion:
If you're developing a CMS style application, you should build your *.ascx controls so that they are compatible with the ASP.NET AJAX Toolkit. That will allow the users to add content to the page without doing a full refresh.
If you really want to make things nice for the user, you should check out Web Parts and ASP.NET AJAX as Web Parts were really designed so that users could customize the content on their pages.

How to access model in jquery

The question here is very simple
This is my view
<%# Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<GetmoreRevamp.BAL.Product>" %>
<link href="<%=Url.Content("~/Content/AddToCart.css")%>" rel="stylesheet"
type="text/css" />
<link href="<%=Url.Content("~/Scripts/jquery-1.4.1.js")%>" type="text/javascript" />
<script type="text/javascript">
function submitForm(formData) {
var tdata = $(formData).serialize();
$.ajax({
type: "POST",
url: '<%= Url.Action("AddToCart","Cart")%>',
data: tdata,
contentType: 'application/json; charset=utf-8',
datatype: "json",
success: function(result) { success(result); }
});
return false;
}
function success(result) {
alert("success:" + result.success);
}
</script>
<% using (Html.BeginForm("AddToCart", "Cart ", Model, FormMethod.Post,
new { onsubmit = "return submitForm('this');" })) {%>
<div class="prishosbtn">
<a rel="prettyPhoto" href="" id="buy">
<%Response.Write("<input type=\"image\" class=\"imgClass\" alt=\"" +
(Model != null && Model.ProductName != null ?
Model.ProductName : "KOEB") + "\" src=\"" +
Url.Content("~/pics/undersider/listevisning/kob-knap.png") +
"\" id=\"ImageButton\" name=\"ImageButton\" />");%>
</a>
</div>
<%}%>
This is my controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GetmoreRevamp.WEB.Models;
using GetmoreRevamp.WEB.Models.BLLModels;
using System.Web.Security;
using System.Security.Principal;
using GetmoreRevamp.WEB.Utilities;
using GetmoreRevamp.BAL;
namespace GetmoreRevamp.WEB.Controllers
{
public class CartController : Controller
{
//
// GET: /Cart/
public ActionResult Index()
{
return View("Cart");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddToCart(Product product)
{
JsonResult result = new JsonResult();
OrderHeader orderHeader =
Session[Constants.CurrentlySessionOrderHeader] as OrderHeader;
if (orderHeader == null)
{
orderHeader = new OrderHeader();
}
if (product != null && product.ProductGuid != null &&
string.Equals(product.ProductGuid, string.Empty))
{
orderHeader.AddOrderLineItem(1, product);
orderHeader.Calculate();
Session[Constants.CurrentlySessionOrderHeader] = orderHeader;
//Default redirection Must be changed when actual view is created
result.Data = true;
}
else
{
//Default redirection Must be changed when actual view is created
result.Data = false;
}
return result;
}
}
}
"Product" is defined in bal. Product contains other business entities. What i simply want to do is to access the model with which view is binded in jquery and then post it to my action method in cart controller. i do not want to post the id of product. I want to post the actual model via jquery to my action method. I am a total newbie in this. so any help and most imp simple solution will be preferred
MVC matches field names to the business object in the action method, so if Product has a ProductID field, there should be a:
Html.TextBox("ProductID")
declaration, or use the TextBoxFor method in MVC 2. I'm pretty sure that's still how it works even when posting using JQuery. The model binder handles the process of taking the form fields and passing them to the product object. But, all of the fields have to be within the form that you are posting to the server, or you have to explicitly pass the parameters where you pass the tdata variable...
HTH.

Resources