Why does this call to my controller not work? - javascript

I have the following JavaScript code on my view in MVC4 project:
jQuery.ajax({
url: "/Object/GetMyObjects/",
data: {
__RequestVerificationToken: jQuery("input[name='__RequestVerificationToken']").val(),
},
type: "POST",
traditional: true
}).success(function (data) {
sfds = JSON.parse(data);
});
and the following method in ObjectController:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetMyObjects()
{
var sfds= _db.SFDS.ToList();
return View(sfds);
}
Why does the controller not get called when the JavaScript is run? Even when I remove the ValidateAntiForgereToken it does not work. In my console I see data returned is null.
I'm having a hard time getting some JSON on my view today.

You aren't returning JSon. You are returning (or attempting to return) a view. You need something like this, in your controller:
return Json(sfds, JsonRequestBehavior.AllowGet);
And, add this to your .ajax() properties:
dataType: "json",

Related

Why Viewbag not show in asp.net mvc view page?

I'm beginner in asp.net mvc,write this java script code for fetch any data from controller:
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: {
'id': 29
},
success: function(color) {
//alert(color);
},
error: function() {
alert('Error occured');
}
});
and write this action in controller:
[HttpGet]
public ActionResult CallService(string id)
{
var idNum = Convert.ToInt32(id);
string color = idNum.ToString();
ViewBag.Myfamily = "razzaqi";
return Json(color, JsonRequestBehavior.AllowGet);
}
in view page write this code:
<h1> Hello Dear #ViewBag.Myfamily</h1>
when i run the project <h1> Hello Dear #ViewBag.Myfamily</h1> not show me ,but i think show me this output:
Hello Dear razzaqi
You are returning JSON not ViewBag. You need to send the "razzaqi" to as part of JSON object. Set up HTML as
<h1> Hello Dear <span id='familyname'></span></h1>
Modify You controller to return myfamily as part of JSON object.
[HttpGet]
public ActionResult CallService(int id)
{
string color = id.ToString();
return Json(new {
color = color
myfamily = "razzaqi"
}, JsonRequestBehavior.AllowGet);
}
Consume the result like
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 29 },
success: function (data) {
$('#familyname').text(data.myfamily)
},
error: function () {
alert('Error occured');
}
});
The Viewbag object is filled into the view, server side when making the view. Your ajax call contacts the server asking about Json data after the view is already made.
So you are too late passing objects to your viewbag if you do it this way...
There are however some workarounds/solutions for this problem:
Let the Controller return the variable in the Json it's returning.
Simple, efficient way to get the data you need
Html helpers etc. Won't work however and sometimes you just need that horrible viewbag...
Reload a partialview when doing the ajax call.
Takes more time to implement, You'll have to create a new action and partialview.
Good when you want more content to change on the call and want to use html helpers etc.

Pass json data from Google Maps to MVC controller with AJAX

I want to store data about addresses and coordinates of markers on map, so I'm creating button in Infowindow which will redirect me to form on another view (also with another controller). I want this form to be already filled with data about coordinates and address. I have function called on button click with AJAX code in it to send JSON data to method in controller. Problem is that after clicking on button controller method isn't called (although function call works properly while debugging). I've been searching a lot for a solution, but I really don't know what did I do wrong.
Call to addMarker:
google.maps.event.addListener(marker, 'click', function (event) {
if(infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: data});
infowindow.open(map, marker);
var buttonAdd = document.getElementById('addButton');
buttonAdd.onclick = function() {
addMarker(event.latLng, address);
}
});
JS function with AJAX:
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress + location) //it's ok, i checked with firebug
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data
})
}
Controller:
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
For now I'm just trying to get to another view without doing anything with recieved data, but it's not working. There's definetely something wrong with ajax or controller. I'm new to MVC, JS and AJAX, so please forgive me if it's something stupid. Thanks in advance.
TL;DR - Clicking on button should result in recieving another view with partially filled (with address and coordinates) form.
Found the problem.
You are using dataType: "json". If you want to post JSON in MVC then you need to create appropriate model with the same format that you are going to post.
Take a look at below example.
Controller :
public class JsonPostExampleController : Controller
{
[HttpPost]
public ActionResult JsonPost(JsonModel data)
{
return View();
}
}
Javascript :
$.ajax({
type: "POST",
url: "JsonPostExample/JsonPost",
dataType: 'json',
data: { 'name': 'ravi' },
success: function (data) { }
});
Model :
public class JsonModel
{
public string name { get; set; }
}
Now as per your requirement, we can not use dataType: "json" as you can't create model according to google's response format for fulladdress and location.
So you need to use dataType: "text" and for that you only need to modify your javascript.
Update your javascript block with below :
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location)
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "text",
data: { JsonStr : data }
});
}
and your controller code remains same as :
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
now you should be able to get your data in string format at server side. If you want JSON server side then you can parse the string.

Deserialize JSON into dictionary in Web Api controller

I have such JSON string:
'{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'
I want to send it to the Web Api Controller without changing using ajax request:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
data: JSON.stringify(sendedData),
dataType: "json"
});
In Web Api I have such method:
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}
And always sendedData == null. Another words: I don't know how to deserialize JSON into (Dictionary<int, List<int>>.
Thank you for answer.
Try this
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
var d1 = Request.Content.ReadAsStreamAsync().Result;
var rawJson = new StreamReader(d1).ReadToEnd();
sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);
}
You can send the data like this:
{"sendedData":[{"key":"1","value":[1,3,5]},{"key":"2","value":[2,5,6]},{"key":"3","value":[5,6,8]}]}
Image of the function in the controller:
Dict
Try it:
Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");
Try using:
public ActionResult Parse(string text)
{
Dictionary<int, List<int>> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<int>>>(text);
return Json(dictionary.ToString(), JsonRequestBehavior.AllowGet);
}
This works when the sent data doesn't have quotes around the indices:
{1:[1,3,5],2:[2,5,6],3:[5,6,8]}
Also make sure that you send an object in the Javascript:
data: {
text: JSON.stringify(sendedData)
},
specify the content type parameter when performing ajax call, dataType is for return result:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
contentType: "application/json; charset=utf-8", //!
data: JSON.stringify(sendedData)
});
You missed the [FromBody] annotation in the sendedData param. Try this:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public object Dict([FromBody] Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}

Call ASP.NET C# Controller Method from Javascript

I have a var toto in a javascript file. And I want to call a C# Controller Method who return a string and of course assign the resulted string to toto.
I tried some ways to achieve this but nothing seems to work.
Somebody can explain me the simpliest way to achieve that ? It's a Windows Azure project.
Many Thanks !
You could use AJAX. For example with jQuery you could use the $.getJSON method to send an AJAX request top a controller action that returns a JSON encoded result and inside the success callback use the results:
$.getJSON('/home/someaction', function(result) {
var toto = result.SomeValue;
alert(toto);
});
and the controller action:
public ActionResult SomeAction()
{
return Json(new { SomeValue = "foo bar" }, JsonRequestBehavior.AllowGet);
}
You have to use JSON:
Controler
public class PersonController : Controller
{
[HttpPost]
public JsonResult Create(Person person)
{
return Json(person); //dummy example, just serialize back the received Person object
}
}
Javascript
$.ajax({
type: "POST",
url: "/person/create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (result){
console.log(result); //log to the console to see whether it worked
},
error: function (error){
alert("There was an error posting the data to the server: " + error.responseText);
}
});
Read more: http://blog.js-development.com/2011/08/posting-json-data-to-aspnet-mvc-3-web.html#ixzz1wKwNnT34

Jquery ajax post to MVC2 action

I'm using the following script to post to and endpoint, it's hitting the breakpoint on the server so I know the routing is correct.
$(document).ready(function() {
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(o),
dataType: 'json',
url: 'home/PingBack',
success: function(result) {
alert(result.success);
}
});
});
The endpoint on the server looks like this.
public JsonResult PingBack(MHolder message)
{
return Json(new { success = "steve"});
}
and the Model looks like this.
public class MHolder
{
public string message { get; set; }
}
I'm sure that in the past the values have been automatically bound to the model, but I can't seem to get anything to be bound atm! Even if I just pass the value as a string, I'm sure it's something silly that I'm missing any ideas?
A few things to notice. You are sending the request as a JSON string (contentType: 'application/json' and JSON.stringify(o)) while on the server you are expecting an object of type MHolder. The default model binder won't do this transformation. You will need to either write a custom model binder capable of deserializing JSON back to an MHolder instance or send the request as key=value pairs (do not stringify):
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
data: o,
dataType: 'json',
url: 'home/PingBack',
success: function (result) {
alert(result.success);
}
});
The code seems OK to me, at first glance.
try using...
data : {message : "Hi from the page."},
...to see if this causes the MHolder instance to be populated.
Also, use something like Fiddler to capture your requests and allow you to see exactly what is being posted.

Categories

Resources