ajax call not posting json data in asp.net - 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.

Related

Access Function From aspx page

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
}

Handle xhr with ASP.NET

I would like to send a POST asynchronously from client side (JavaScript) to server side (ASP.Net) with 2 parameters: numeric and long formated string.
I understand the long formated string must have encodeURIComponent() on it befor passing it.
My trouble is I want to embed the long encoded string in body request and later open it from C# on server side.
Please, can you help me? I'm messing too much with ajax, xhr, Request.QueryString[], Request.Form[], ....
First, create an HTTPHandler:
using System.Web;
public class HelloWorldHandler : IHttpHandler
{
public HelloWorldHandler()
{
}
public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
//access the post params here as so:
string id= Request.Params["ID"];
string longString = Request.Params["LongString"];
}
public bool IsReusable
{
// To enable pooling, return true here.
// This keeps the handler in memory.
get { return false; }
}
}
Then register it:
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx"
type="HelloWorldHandler"/>
</httpHandlers>
</system.web>
</configuration>
Now call it - using jQuery Ajax:
$.ajax({
type : "POST",
url : "HelloWorldHandler.ashx",
data : {id: "1" , LongString: "Say Hello"},
success : function(data){
//handle success
}
});
NOTE Totally untested code but it should be very close to what you need.
I just tested and it works out of the box. This is how I called it:
<script language="javascript" type="text/javascript">
function ajax() {
$.ajax({
type: "POST",
url: "HelloWorldHandler.ashx",
data: { id: "1", LongString: "Say Hello" },
success: function (data) {
//handle success
}
});
}
</script>
<input type="button" id="da" onclick="ajax();" value="Click" />

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.

ASP.NET MVC Controller FileContent ActionResult called via AJAX

The setup:
The controller contains a method public ActionResult SaveFile() which returns a FileContentResult.
What works:
The view contains a form, which submits to this action. The result is this dialog:
What doesn't work:
The view contains some javascript to do an AJAX call to the same controller action where the form would post. Rather than triggering the aforementioned dialog, or even the AJAX success function, the response triggers the AJAX error function, and the XMLHttpRequest.responseText contains the file response.
What I need to do:
Make the request for the file using AJAX, and end up with the same result as when submitting a form. How can I make the AJAX request provide the dialog that submitting a form shows?
Here's a quick example I made up. This is the concept LukLed was talking about with calling SaveFile but don't return file contents via ajax and instead redirect to the download.
Here's the view code:
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// hide form code here
// upload to server
$('#btnUpload').click(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '<%= Url.Action("SaveFile", "Home") %>',
success: function(fileId) {
window.location = '<%= Url.Action("DownloadFile", "Home") %>?fileId=' + fileId;
},
error: function() {
alert('An error occurred uploading data.');
}
});
});
});
</script>
<% using (Html.BeginForm()) { %>
<div>Field 1: <%= Html.TextBox("field1") %></div>
<div>Field 2: <%= Html.TextBox("field2") %></div>
<div>Field 3: <%= Html.TextBox("field3") %></div>
<button id="btnUpload" type="button">Upload</button>
<% } %>
Here's the controller code:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult SaveFile(string field1, string field2, string field3)
{
// save the data to the database or where ever
int savedFileId = 1;
// return the saved file id to the browser
return Json(savedFileId);
}
public FileContentResult DownloadFile(int fileId)
{
// load file content from db or file system
string fileContents = "field1,field2,field3";
// convert to byte array
// use a different encoding if needed
var encoding = new System.Text.ASCIIEncoding();
byte[] returnContent = encoding.GetBytes(fileContents);
return File(returnContent, "application/CSV", "test.csv");
}
public ActionResult About()
{
return View();
}
}

Resources