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

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.

Related

Submitting Json to Spring MVC Controller returning jsp as ajax response string

I am creating Spring mvc app. I am submitting JSON string to controller through AJAX. What I want is to redirect the page to different JSP page.
Right now I am returning the view from controller but instead of redirecting it is returning response to previous AJAX request.
Spring Controller
#RequestMapping("/hello")
public String hello() {
return "powerseries";
}
Javascript/Ajax
$(document).ready(function(){
$('#getData').click(function(){
var aa=JSON.stringify(answer);
$.ajax({
type: "POST",
url: "hello",
contentType: "application/json",
dataType:'json',
data:aa,
cache: false,
processData:false,
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
}
});
});
});
console.dir(answer);
Browser Console
When you are using AJAX, your MVC should return a special JSON response.
eg:
#RequestMapping("/hello")
#ResponseBody
public Map hello() {
m.put('my_redirect', 'the new url');
return m;
}
then handle this response in your AJAX's handler. Use javascript's window.location.href = resp.my_redirect; to go to the new url.
If you want to redirect to other jsp page , use redirect inside controller method.
#RequestMapping("/hello")
public String hello() {
// return "powerseries";
return "redirect:powerseries";
}
// Add method to controller .
#RequestMapping("/powerseries")
public String returnPowerseries() {
return "powerseries";
}
or just use $("html").html(response); if you want to entirely change your document html.

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.

Why does this call to my controller not work?

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",

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

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

Categories

Resources