I have implemented the following $.Post Jquery function in my asp.net page MAIN Page.aspx
the
$.post({ url: "MAIN Page.aspx",
data: { "Status":ddl },
contentType: "application/json; charset=utf-8",
dataType: "json",
});
where ddl is my data to be posted ...i have placed this $.post in the document.ready() and i tried accessing the posted value in the code behind as
var status= Request.Form.Get["Status"]...
but when i run the code the value of the status is null..
please help and guide if i am correct in my implementation of the logic
Try like this:
$.post('MAIN Page.aspx', { status: ddl }, function(result) {
alert('success');
});
and on your server:
var status= Request.Form["Status"];
Also you haven't shown what this ddl javascript variable is and how you assigned it a value but make sure that it is not a complex object but it contains some simple type.
Alternatively if you want to use the $.ajax method:
$.ajax({
url: 'MAIN Page.aspx',
type: 'POST',
data: { status: ddl },
success: function(result) {
alert('result');
}
});
Related
I have a ajax code that fills a dropdownlist and I use mvc c#.
When I call to my method from ajax and I have an url in the directions bar without parameters the code works correctly, but if I have a parameter in url in the directions bar this not working and appears this error:
"{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}".
Here's my code:
$.ajax({
url:"../Records/myList",
type: "POST",
dataType: 'json',
contentType: 'application/json',
// data: JSON.stringify(Data),
success: function (resul) {
Function(resul);
},
error: function (message) {
}
});
My url: http://localhost:123/Record/EditRecord ->> so it's works
My other url: http://localhost:123/Record/EditRecord/1 ->> It does not work like this
Thanks in advance.
From given second URL (which doesn't work) I assume that you want to use jQuery AJAX with HttpGet method. The URL pattern matches this route:
http://localhost:123/{controller}/{action}/{id}
which id treated as UrlParameter.
Hence you need to use action argument & data representing URL parameter values, like this example:
Controller
[HttpGet]
public ActionResult EditRecord(int id)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "GET",
dataType: 'json', // response type
contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type
data: { id: 1 },
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Alternatively a direct usage of URL parameter is applicable for GET methods without specifying data content:
View (JS)
$.ajax({
url: "Record/EditRecord/1",
type: "GET",
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
NB: Use jQuery.get for simplified version:
$.get("/Record/EditRecord/1", function (result) {
Function(result);
}, "json").error(function (message) { // throw error
});
PS: This is an example for HTTP POST request if you're looking for proper POST method with AJAX.
Controller
[HttpPost]
public ActionResult EditRecord(Record rec)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "POST",
dataType: 'json', // response type
contentType: 'application/json; charset=utf-8', // header content type
data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}),
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Reference:
Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX
i cant see any fault in the code but i suggest to try let the param come with it's name at server either if you choose to use data propery (of ajax function):
{key1: 'value1', key2: 'value2'}
or you use string query:
page?name=ferret&color=purple
bacuse you've just say that first method was work i assume there is no need to check POST/GET method.
EDIT:
be award to this.
I'm posting data with ajax and it's successfully posted. At the controller side I'm filling a ViewBag with data posted but i'm having a problem getting data from ViewBag.
Here's Ajax Code:
$.ajax({
type: "POST",
url: '../Home/getExistUsersFromJSON',
data: JSON.stringify({ jsonString: JSON.stringify(array) }),
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
// Alert that it was succesful!
var jsonList = '#Html.Raw(Json.Convert(ViewBag.newUsers))';
var jsList = JSON.parse(jsonList);
bootbox.dialog({
message: jsList,
title: "Utilisateurs",
buttons: {
success: {
label: "Success!",
className: "btn-success"
}
}
});
}
});
And this is the controller side
[ActionName("getExistUsersFromJSON")]
public void getExistUsersFromJSON(string jsonString)
{
IList<newUser> ctm =
new JavaScriptSerializer().Deserialize<IList<newUser>>(jsonString);
ViewBag.newUsers = ctm.ToList();
}
ViewBag is just an object that gets passed to the view when you render the page.
It doesn't make any sense to use that with AJAX; your server-side Razor code runs on initial server render only.
You need to server JSON as the response (using Json()).
I need to find a way to post a serialized form and an extra param to controller via ajax request. I can use serialize() on the form, or just send object with params, but cannot send both. How would I accomplish this?
For example I want my controller params to be as follows:
myaction(int siteID, Model model).
Pass what ever extra parameters you want along with form data as follows:
$.ajax({ type: 'POST',
url: "/MyController/Process",
data: $("form").serialize() + '&id=12345' ,
success: function () { alert("Successful"); },
dataType: "json"
});
Hope this helps..
You need to use something like this:
var dataToPost = $('#formID').serialize() + "&siteID=" + "23";
Now use this dataToPost variable in jquery ajax method like this:
$.ajax({
url: //url,
type: //'POST',
dataType: //'html',
async: true,
data: dataToPost,
cache: false,
}).success(function (response, status, xhr) {
}).fail(function (e) {
console.log(e);
});
I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },
$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information
Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},
try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.