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}
Related
I want to fetch Session variable value from an mvc controller actionresult which returns a cshtml view. This ajax call is connected in a button click and is calling from a different cshtml.
function accountLogin() {
$.ajax({
url: accountLogin,
async: true,
type: 'POST',
cache: false,
success: function (data) {
var testUser = #Session[Keys.accountrole];
alert(testUser);
$("#navigationbar").empty();
$("#navigationbar").html(data);}
C# Code
[HttpPost]
public ActionResult accountLogin(){
Session[Keys.accountrole] = "value";
return View("_viewpage");
}
The curent implementation is reaturning either undefined session variable or it will display the #session keyword itself not the value in it.
You can only access Session on the server side. So you have to get a Session variable value inside of the action and retun it back as a json value
Try this
[HttpPost]
public IActionResult accountLogin(){
//I don't understand why you need it
Session[Keys.accountrole] = "value";
var sessionAccountRole=Session[Keys.accountrole];
return OK( {accountRole=sessionAccountRole} );
// or if you use an ancient net
return Json ( new {accountRole=sessionAccountRole} );
// or maybe
return new JsonResult {accountRole=sessionAccountRole};
}
and ajax
success: function (data) {
var testUser = data.accountRole;
alert(testUser);
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 have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty
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
}
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).