In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
Related
Passing dynamic objects from client-side to C#
hello friends,
i'm searching for passing a dynamic data, whatever data sent which is value type or reference type or both,
lets see a example as simple
client-side
1st request
var model = {
Id: 10,
Name: 'John'
Active: true
};
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: JSON.stringify(model)
});
2nd request
var model = {
Email: 'm#m.net'
CurrentSalary: 1500,
CurrencyType: 1
};
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: JSON.stringify(model)
});
3rd request
var id = '1e575923-d6cf-447e-9163-f7885655e4f5';
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: {Id : id}
});
server-side
public JsonResult GetData(dynamic model)
{
// my code here...
}
Question:
I need a way to receive a dynamic data.
Is it possible to send dynamic data from client-side(using jquery ajax) to Server-side C# ?!
Please let me know if you have any idea about this question.
Note: I will not vote down, for any answer
i use this for call server-side
var data = {
Name: 'Sam',
Age: "26"
};
$.ajax({
url: "http://localhost:8081/Home/PostData",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
alert(data);
},
error: (xhr, tt, tm) => errorHandler(xhr, tt, tm)
});
function errorHandler(xhr, tt, tm) {
console.dir(xhr, tt, tm);
};
Thank you so much, UW.
I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live
I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
I am posting data through ajax to a action, but the problem I am not able to get the data posted through ajax in my controller action. While debugging, the call gets transferred to action but I dont get anything in data not even 'null'.
here is my ajax call,
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: { country: 2, amount: 4.02 },
datatype:JSON,
success: function (data) {
alert("hiiii"+data);
}
});
and my action,
[HttpPost]
public JsonResult PostAmount(int country,double amount)
{
AllocationViewModel mod = new AllocationViewModel();
return Json(mod);
}
Try this:
var dataToPost = "{ country:'" + 2 + "', amount:" + 4.02 + "}";
$.ajax({
url: #Url.Action("PostAmount", "Deal")',
type: "POST",
dataType: 'json',
data: dataToPost,
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
alert("hi"+ data);
}
});
try the following:
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: { "country": "2", "amount": "4.02" },
datatype:JSON,
success: function (data) {
alert("hiiii"+data);
}
});
or the best solution is to save the values in an object and use the jquery function "stringify" and then send the values over. that should work.
try putting json in quotes
$.ajax({
type: 'POST',
url:'#Url.Action("PostAmount", "Deal")',
data: { country: "2", amount: "4.02" },
dataType:"json",
traditional:true,
success: function (data) {
alert("hiiii"+data);
}
});
You could also use JSON.stringify(yourObject) on your object to make it a JSON object. This makes it easier to create objects in javascript and pass then into the data parameter of your post request.
Also use a string for the datatype parameter (https://api.jquery.com/jquery.post/), as suggested in the answers above.
var dataToPost = { country: 2, amount: 4.02 };
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: JSON.stringify(dataToPost),
datatype: 'json',
success: function (data) {
alert("hiiii"+data);
}
});
The other way around is JSON.parse(yourJsonObject). This way you can parse a JSON string into a Javascript object.
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 },