I have 3 forms, Associate.cs, HomeController.cs, Index.cshtml.
I load a DataTable from Associate.cs and use this code to get it into JSON format.
public string GetAssociateFromDB()
//code omitted
var json = JsonConvert.SerializeObject(dt, Formatting.Indented);
jsonData = json;
}
}
return jsonData; //return is good
I call this from HomeController.cs.
public JsonResult GetJsonData()
{
Associate associate = new Associate();
string jsonData = associate.GetAssociateFromDB();
System.Diagnostics.Debug.WriteLine(jsonData); //for testing purposes
return Json(jsonData, JsonRequestBehavior.AllowGet); //need to pass to `Index.cshtml`
}
However, this code doesn't get hit unless I put the method in this block:
[HttpGet]
public ActionResult Index()
{
GetJsonData(); //if not called here, it never gets hit.
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
Then, I try to pass it to Index.cshtml, via $.getJSON method, but it never reaches it.
jQuery(document).ready(function () {
var mydata;
$.getJSON('#Url.Action("HomeController", "GetJsonData")', function(data) {
datatype: 'json'
mydata = data;
console.log(data); //unsure if this works or not.
});
I am then trying to supply that data for a jqGrid (this is just under the above code):
$("#grid").jqGrid({
data: mydata,
datatype: "json",
width: '100%',
colNames: ["Seq ID", "Fund ID", "Name", "Fund", "Bonus", "Allocation", "Blank", "Begin", "End"],
colModel: [{
name: 'seqid',
index: 'seqid',
editable: true,
},....//Code omitted
I can't seem to get the data from the Controller to Index.cshtml.
I have read on a blog that there is a problem with cache in IE 8, which is what I am testing in, but I'm pretty sure that's not my initial problem.
I've read the jQGrid documentation and searched many times, but the only example is for this kind of thing is for PHP or in a different context. I tried putting [HttpGet] above the GetJsonData method, and that did not work either.
It's also important to note I haven't written much(any) jQuery before.
Try this below code.
Url.Action('actionname','controllername')
javascript:
$(document).ready(function () {
var mydata;
$.getJSON('#Url.Action("GetJsonData", "Home")', function(data) {
datatype: 'json'
mydata = data;
gridFn(data);
});
function gridFn(data)
{
//here grid code
}
Related
I am new at MVC programming. Currently working on VS2017. I am trying to post data from View in JSON String format to Controller. When checked at Jquery Console the data is there but at controller it is received as null.
This is my Jquery Ajax
$('#btnSave').click(function () {
var Studentdata = { JsonStr: addStudent }
console.log(JSON.stringify(Studentdata))
$(this).val('Please wait...');
$.ajax({
url: '/Students/SaveStudents',
type: "POST",
data: JSON.stringify(Studentdata),
dataType: "JSON",
traditional: true,
contentType: 'application/json;charset=utf - 8',
}); });
This is the Json String which is shown on the console on Click of Save Button
{"JsonStr":[{"StudentId":"1","Name":"Pravin","Email":"pra#gmal.com"},{"StudentId":"2","Name":"ramesh","Email":"ram#ymail.com"},{"StudentId":"3","Name":"suresh","Email":"s#mail.com"},{"StudentId":"4","Name":"parvesh","Email":"peter#h.com"}]}
Below is how my controller action is:
[HttpPost]
public IActionResult SaveStudents(string JsonStr)
{
// conditions to be written
return View();
}
Please, help me to resolve it. I tried a lot.
You can try this way
Step 1. Make sure that you have Studentdata class in server side.
[HttpPost]
public IActionResult SaveStudents(List<Studentdata> JsonStr)
{
// conditions to be written
return View();
}
Step 2. Adjust format contentType: 'application/json; charset=utf-8'`, as well. I see that it contains unnecessary spaces.
BTW, This post is very useful.
I am making ajax call like this
deleteAge(item: any): string {
$.ajax({
method: "POST",
url: 'DeleteAge',
data: item.Id(),
success: (response) => {
toastr.success("ready soon");
},
error: (event) => {
toastr.error("Error occured ");
}
}).always(() => {
});
return "";
}
Here is my method in controller which is currently nothing almost implemented
[HttpPost]
public ActionResult DeleteAge(string id)
{
throw new Exception();
}
when i run the code then in my controller i dont get any id.. its null. when i debug my javascript code then this code item.Id() is not blank. Even if i pass hardcoded value to data in ajax call still controller gets null. What is wrong?
Rather than using:
data: item.Id(),
I'd suggest using:
data: { id: item.Id()},
This way the id value is associated with the id name - allowing model binding to work correctly.
Pass parameters like json format in ajax
replace data: item.Id() with data: {id: 1}
I have the following chtml code to an action in a controller. The data is being sent by ajax to the action.
The chtml part:
<li>
<button id="abandon-popup" onclick="Transfer(#Model.Id)">
Transfer <i class="icon-arrow-right"></i>
</button>
</li>
The function Transfer:
function Transfer(modelId) {
//alert(modelId);
$.ajax({
type: "GET",
url: "/Internet/Transfer",
data: "id=" + modelId,
success: function (responsedata) {
alert("ok");
window.location.href = responsedata.newUrl;
},
error: function (data) {
console.log("KO");
}
})
}
The action in the controller:
public ActionResult Transfer(long id)
{
*some actions*
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
}
However I am getting a 500 internal error on this:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet
Any idea how to correct this?
Use this
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml",
commonModel
)}, JsonRequestBehavior.AllowGet);
By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request.
Try this following:
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
into
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) }, JsonRequestBehavior.AllowGet);
Change GET method to POST method the following way:
Client side:
function Transfer(modelId) {
//alert(modelId);
$.ajax({
type: "POST",
url: "/Internet/Transfer",
data: {id: modelId},
success: function (responsedata) {
alert("ok");
window.location.href = responsedata.newUrl;
},
error: function (data) {
console.log("KO");
}
})
}
Controller side:
[HttpPost]
public ActionResult Transfer(long id)
{
*some actions*
return Json(new { newUrl = PartialView("~/Views/Shared/Partials/Leads/_TransferPopup.cshtml", commonModel) });
}
I'm new in JQuery and AJAX. I tried to fill a DropDownList using AJAX in ASP.NET MVC 4 and it gives me this error:
The ObjectContext instance has been deleted and can not be used for operations that require a connection.
and here is my script:
function LoadFlights() {
var $flight = $('#IDFLIGHT');
$flight.empty();
$flight.append($('<option></option>').val('').html('Please Wait...'));
$.ajax({
url: '/Flight/GetFlightList',
type: 'POST',
data: {},
dataType: 'json',
success: function (d) {
$flight.empty();
$flight.append($('<option></option>').val('').html('Select Flight'));
$.each(d, function (i, val) {
$flight.append($('<option></option>').val(val.IDFLIGHT).html(val.DATEFLIGHT));
});
},
error: function () {
}
});
}
And this is the action in the controller Flight I call:
public JsonResult GetFlightList()
{
FlightService flightService = new FlightService();
var all = flightService.GetAll();
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
The variable all has data but it still give me the error mentioned above.
Thank you
You should use return Json(all,JsonRequestBehavior.AllowGet);, just passing the list data to the constructor will not convert it to JSON object.
P.S. the funtion Json() will return JsonResult
Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).