jquery AJAX sent data in key value pair - c#

In my aspx page, i have the js like this :-
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = "{'datakey':'hello'}"
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});
</script>
In the same webpage code behind class file ,i have the webmethod defined like this:-
[WebMethod]
public static string SendFile(string key, string data)
{
return data;
}
For some reason, i am able to get the data in the alert used on the html side. alert(msg); is giving me nothing and i am expecting to get the passed value back. In this case it should be 'Hello'.
I am missing something very small here, please help me out here.

Alter these.
The AJAX Call
$(document).ready(function () {
$("#btnLoad").click(function (evt) {
var dataForAjax = "{'datakey':'hello'}";
$.ajax({
contentType: "application/json",
data: dataForAjax,
type: "POST",
url: 'Test1.aspx/SendFile',
success: function (msg) {
var msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg.datakey);
}
});
evt.preventDefault();
});
});
The WebMethod
[WebMethod]
public static object SendFile(string datakey)
{
return new
{
datakey = datakey
};
}
Hope this helps.
Update:
`evt.preventDefault is for preventing postback in case your control was something like input type="submit" or asp:Button
.d is ASP.NET 3.5+ feature to prevent XSS vulnerability. ( link here )
The return type is object for the web method for automatic serialization ( link here )
Also you could omitdataType in $.ajax call but contentType is an absolute necessity ( link here )

This:
var dataForAjax = "{'datakey':'hello'}"
Should be:
var dataForAjax = {'datakey':'hello'}
AJAX does not (by default anyway) send json - it sends FORM INPUT elements! jQuery is nice and will convert javascript objects into that for you.
If you really need to you can send json, but I really doubt you do, it's rare to do that.

When you send data to method you must send apropriate key-value pairs, using object in Javascript.
Examle for you method:
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = {'key' :'datakey', 'data' : 'hello'};
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});

Related

How to refresh a particular division while using MVC

I have tried different ways to refresh a particular division in MVC.
1. Using HTML Action Link
2. Ajax Action Link
3. method
Please help me resolve this issue.
My Code is as follows:
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>
<script>
function updateAsyncCategoryUpdate() {
var url = '/Home/HomePage';
$.ajax({
url: url,
//data: { value: '1234' }, //if there are any parameters
dataType: "html", //or some other type
success: function () {
window.location.reload(true);
// or something in that area, maybe with the 'data'
},
error: function () {
//some derp
}
});
}
</script>`
#Ajax.ActionLink(item.Name, "HomePage", new { CATEGORy = item.Name }, new AjaxOptions {HttpMethod="GET", OnSuccess = "updateAsyncCategoryUpdate('item.Name')" })
You can append the success function.
This replaces content of div
success: function (data)
{
$('#divSelector').html(data);
}
This appends content of div
success: function (data)
{
$('#divSelector').append(data);
}
Your script function does not have parameter and you send Item.Name to it.(although you dont use this parameter inside the script!)
First, define parameter for updateAsyncCategoryUpdate function.
Secomd,Add a container element(like div) to your page with specific id(resultDiv for example) and replace the success code of your scrip with this:
success: function(result){
var myDiv = $('#resultDiv');
myDiv.empty();
myDiv.prepend(result);
}

Set value of Viewstate from Javascript

I am working on asp.net application. Where for a page I have to clear the value of the controls(like textbox and dropdownlist,etc), also i have to remove the value of a ViewState. Initailly i was doing it from codebehind, so o problem was there. But now the problem arise when i tried reset the value of controls using client side , say
document.getElementById('<%= txtTextBox.ClientID %>').value ='';
but the problem i am facing is that i cannot set the viewstate value from clientside.
my i have to clear to viewstate one is a simple variable say ViewState["NameOfUser"],and another one is converting a datatable into viewstate say,
ViewState["dataTable"] = dt;
Thanks and regards
You simply can not assign value in client side.
Either you have to pass it through hidden field while submitting form or
Call ajax from javascript and access the ViewState server side.
I found this way via ajax request:
Credits: https://forums.asp.net/t/1991868.aspx?Set+value+of+Viewstate+from+Javascript+or+Jquery
ViewState["dataTable"] = dt;
Javascript:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#Button1").click(function () {
//clear datatable
$.ajax({
type: "POST",
url: "WebForm1.aspx/ClearDataTable",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('cleared');
}
});
//clear other values.....
//............
});
})
</script>
On codebehind:
[WebMethod]
public static void ClearDataTable()
{
HttpContext.Current.Session["datatable"] = null;
}
Hope that it helps!

Get a resource string based on javascript value

Is it possible to accomplish something like this?
<script type="text/javascript">
function getValues( keysArray ) {
var valuesArray = new Array(keysArray.length);
for (var i = 0; i < keysArray.length; i++) {
valuesArray[i] = #this.LocalResources(keysArray[i]);
}
return valuesArray;
}
getValues function will get executed on the browser. Razor is going to execute before the page is send to the browser. there for this wouldn't work.
If you wanted to call the LocalResources method on the server you could to expose a controller action and perform a ajax request from the client.
Perhaps something like this on the browser:
Javascript
function getValues( keysArray ) {
$.ajax({
url: "/Controller/getValues",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify({ "keysArray" : keysArray }),
success: function (result) {
//result obj is your array of resources
}
});
MVC Controller
public JSONResult getValues(object keysArray)
{
///Build respurce array here
}
Ajax request, or;
loading the list of necessary Resources keys in page and then accessing them by JS.

JQuery not returning successfully

This is the call to ajax for posting my form.
<script type="text/javascript">
$(function () {
$("#GetReport").click(function () {
var d = {input:$("#frm").serialize()};
$.ajax({
type: 'POST',
url: '/Questions/Answer',
data: JSON.stringify(d),
dataType: "json",
contentType: "application/json",
success: function (result) {
alert(result);
}
});
});
});
</script>
and this is my action
[HttpPost]
public ActionResult Answer(string input)
{
return Content("Success");
}
When I press the relevant button, the action gets called but when the value returns, I expect an alert to be displayed saying "Success" but I get nothing despite my action getting called.
Try dataType: "text", since you seem to be returning a plain string (that is not in JSON format), and dataType specifies the expected response format, not the request format. (Or just remove the dataType option, in which case jQuery will make its own best guess at the what the response format is once it sees it.)
[HttpPost]
public ActionResult Answer(string input)
{
return Json("Success", JsonRequestBehavior.AllowGet);
}

ASP .NET MVC3 ajax call same function from various pages

How can I call the same action using ajax from different pages?
type: 'POST',
url: 'Notification/GetRecentNotifications/'
I'm currently using the code above to call my action. It works for my application's home page, but when I change to other page, this doesn't work. Can anybody give me a solution? Thanks before.
Heres what I usually do to point to which controller & action to call within an ajax jquery call...
$.ajax({
type: "POST",
url: '#(Url.Action("Action", "Controller"))',
success: function (data) {
}
});
Use Url.Action() to build links
Put the code in a ajax.js file in your scripts directory then reference it in the pages where you need to use the methods in that file. Then, put any server side logic for your ajax calls in an AjaxController For example:
ajax.js
function foo() {
var model = { };
$.ajax({
url: '#Url.Action("Foo", "Ajax")',
type: "POST",
data: JSON.stringify(model),
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
}
AjaxController.cs
public class AjaxController : Controller
{
[HttpPost]
public JsonResult Foo(FooModel model)
{
string message = _ajaxService.Foo(model);
return Json(message);
}
}
In the example above _ajaxService is a service layer object that contains the logic to handle your ajax requests. Below is how to use the function in your view:
SomeView.cshtml
<script type="text/javascript" language="javascript" src="#Url.Content("~/Content/Scripts/ajax.js")"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#button').click(foo);
});
</script>
If there is additional logic to pass data to the ajax method that is reused, you should probably put it in a partial view and reference that from every view that needs it.

Categories