Pass Data by AJAX to Controller in MVC - javascript

I'm trying to pass data to controller for further processing but I get null in controller, however debug of js (ajax) shows the number anyway. What might be the problem?
Ajax:
$('.toggler_btn').on('click', function (event)
{
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: "/List/GetSubItems",
type: "POST",
contentType: "html",
dataType: "text",
data: '{"id":"' + id + '"}', // here it show the data, like 5 or some other number
success: function (data)
{
$('.element_wrapper [data-id="' + id + '"]').html(data);
}
})
$(this).html('-');
}
else $(this).html('+');
});
Controller:
[HttpPost]
public ActionResult GetSubItems(string id) // here I get null
{
int pID = 0;
int.TryParse(id, out pID);
List<H_Table> list = new List<H_Table>();
foreach (var item in db_connection.H_Table.Where(i => i.PARENT_ID == pID))
{
list.Add(item);
}
return PartialView(list);
}

$('.toggler_btn').on('click', function (event) {
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: '/List/GetSubItems',
type: 'POST',
dataType: 'json',
data: '{"id":"' + id + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.element_wrapper [data-id="' + id + '"]').html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("responseText=" + XMLHttpRequest.responseText + "\n textStatus=" + textStatus + "\n errorThrown=" + errorThrown);
}
});
$(this).html('-');
}
else $(this).html('+');
});
Use this one just copy and paste

Change your content type to "text" and change the data as well.

Change data type to "application/json" and data to this :
data :{
id : id
}

Your AJAX request has set contentType: "html" but you are actually sending JSON (with data: '{"id":"' + id + '"}'). And your controller is receiving a string.
So either change your AJAX call to send a raw string:
contentType: "text",
data: { id: id }
...or update your controller to receive JSON. This latter can be achieved by creating something like this:
public ActionResult GetSubItems(ViewModel model)
public class ViewModel {
public string Id { get; set; }
}
EDIT: also, for reference, you might want to see the difference between contentType and dataType.

Related

How to save data from JavaScript to C#

I have problem with saving new record to the database, using C# controller.
Here is the JS code:
<script type="text/javascript">
function save1(input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: ' #Url.Action("Saving", "LanguagesController")',
type: "POST",
data: { name: input1, level: input2 },
dataType: "text",
success: function (result) {
alert("Yess!!")
},
error: function (request, error) {
alert("Noooo : " + error);
}
});
alert("End of function");
}
Here is my C# controller:
[HttpPost]
public ActionResult Saving(string name, string level)
{
Language lan = new Language();
lan.name_of_language = name;
lan.level_of_difficality = level;
db.Languages.Add(lan);
db.SaveChanges();
return View(db.Languages.ToList());
}
Thank you in advance
I can't see anything wrong with what you have (but are you really expecting text back?), but this would be better:
HTML:
<a class="btn" data-url="#Url.Action("Saving","LanguagesController")">Save</a>
Javascript:
$('a[data-url]').on('click',function() {
var url=$(this).data('url');
var input1=$('something').val();
var input2=$('somethingelse').val();
save1(url,input1,input2);
});
function save1(url, input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: url,
type: "POST",
data: { name_of_language: input1, level_of_difficality: input2 },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(result) {
alert("Yess!!")
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("Noooo : " + textStatus + " " + errorThrown);
});
alert("End of function");
}
C#:
[HttpPost]
public JsonResult Saving(Language lan)
{
db.Languages.Add(lan);
db.SaveChanges();
return Json(db.Languages.ToList());
}
PS. difficality is not spelled correctly.
Your problem is you're passing a control rather than a value
function save1(input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: ' #Url.Action("Saving", "LanguagesController")',
type: "POST",
data: { name: getElementById('input1').value , level: getElementById('input2').value }, //changed from control to value
contentType: "application/json; charset=utf-8", // define contenttype
dataType: "json", //and the type you're expecting
success: function (result) {
alert("Yess!!")
},
error: function (request, error) {
alert("Noooo : " + error);
}
});
alert("End of function");
}
And at server side, you must get your model as input:
[HttpPost]
public ActionResult Saving(Language lan)
{
db.Languages.Add(lan);
db.SaveChanges();
return db.Languages.ToList();
}

jQuery Ajax POST request

I am trying to get the following code to send variables to a PHP page via POST. I am not quite sure how to do it. This is my code sending data via GET and receiving it via JSON encoding. What do I need to change to pass variables to process_parts.php via POST?
function imagething(){
var done = false,
offset = 0,
limit = 20;
if(!done) {
var url = "process_parts.php?offset=" + offset + "&limit=" + limit;
$.ajax({
//async: false, defaults to async
url: url
}).done(function(response) {
if (response.processed !== limit) {
// asked to process 20, only processed <=19 - there aren't any more
done = true;
}
offset += response.processed;
$("#mybox").html("<span class=\"color_blue\">Processed a total of " + offset + " parts.</span>");
alert(response.table_row);
console.log(response);
imagething(); //<--------------------------recursive call
}).fail(function(jqXHR, textStatus) {
$("#mybox").html("Error after processing " + offset + " parts. Error: " + textStatus);
done = true;
});
}
}
imagething();
The default method is GET, to change that, use the type parameter. You can also provide your querystring properties as an object so that they are not immediately obvious in the URL:
var url = "process_parts.php";
$.ajax({
url: url,
type: 'POST',
data: {
offset: offset,
limit: limit
}
}).done(function() {
// rest of your code...
});
Try This
$.ajax({
url: "URL",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(ty),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});

AJAX post data is null in controller mvc

I try to send a JSON object back to the server. This is my AJAX call:
$.ajax({
url: '/Home/NewService',
async: false,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCES");
}
});
The evaluation of JSON.stringify(props) in the browser's debugger is
"[{"name":"firstName","value":"firstValue"}]"
This is the method in the controller which is being called:
[HttpPost]
public void NewService(dynamic json)
{
Response.Write(json);
}
The problem I have is that always the json variable from above is an empty object.
The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong.
Thank you.
I don't think you can bind to a dynamic type the way you're trying to. You can try to create a class that maps your data, something like:
public class Content
{
public string Name { get; set; }
public string Value { get; set; }
}
Now in your action:
[HttpPost]
public ActionResult NewService(Content[] data)
{
// sweet !
}
And in your js like Olaf Dietsche said you need to specify your contentType:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '/Home/NewService',
contentType: "application/json",
async: true,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
According to jQuery.ajax(), the default content type is is application/x-www-form-urlencoded. If you want to send the data as JSON, you must change this to
$.ajax({
url: '/Home/NewService',
contentType: 'application/json',
...
});
Use the following code to solve this problem
Ajax Call
function SaveDate() {
var obj = {};
obj.ID = '10';
obj.Name = 'Shafiullah';
$.ajax({
url: '/Home/GetData',
dataType: "json",
type: "Post",
contentType: 'application/json',
data: JSON.stringify({ ID: obj.ID, Name: obj.Name }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data.id + ' , ' + data.name);
},
error: function (xhr) {
alert('error');
}
});
}
My controller action method
[HttpPost]
public IActionResult GetData([FromBody] Employee employee)
{
return Json(employee);
}

Unable to fetch data from TempData

i am saving some value in TempData in my controller_method. but when i access it in view , i get nothing...
Controller code:
public ActionResult Read_Surah()
{
TempData["Verse_Count"] = obj1.Total_Ayahs; // int data
return Json(new { key = Records }, JsonRequestBehavior.AllowGet);
}
view part:
$.ajax({
url: "../Gateway/Admin_Mgmt?Action_Code=" + 115 + "&S_ID=" + surah_id,
type: 'Post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: '',
success: function (result)
{
var mera_obj = result.key;
contents = mera_obj;
mera_obj.size;
#{
string q = (string)TempData["Verse_Count"];
}
alert(#q);
return false;
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error : " + xhr.responseText); },
});
but its showing 'undefined' in alert...
Do not use TempData to pass value from Controller to view.
Use ViewBag, as TempData is used to provide you data from controller to controller or Action to Action.
See the link for reference:
http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-2cplusViewBagplusandplusTem

How to send the selected values from list box using ajax

I need to send the multiple selected data from list box using ajax in mvc. I get the selected data. I dont know how to send the data ajax to controller. My code is below:
var Students= [];
var x = document.getElementById("ListBox");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected == true) {
Students.push(x.options[i].text)
}
}
$.ajax({
url: '',
type: 'POST',
data: { id:studenid, class: class, Students: Students},
dataType: 'json',
success: function (data) {
}
}); // id:studenid, class:classs values are send it properly how to add the students?
var Students= [];
var x = document.getElementById("ListBox");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected == true) {
Students.push(x.options[i].text)
}
}
$.ajax({
type: "POST",
data: {StudentList:Students},
url: "index.aspx",
success: function(msg){
alert(msg);
}
});
//Send width param name
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: { paramName: Students},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
}
});
//Get value
[WebMethod]
public static string GetValue(string paramName)
{
}
In The Generic Handler
//Send
$.ajax({
type: "POST",
url:'/MyHandler.ashx?students=Students,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
}
});
//Get
public void ProcessRequest(HttpContext context)
{
string students= (string)context.Request["students"];
}
Your url:'' field is empty. You need to add some URL there for which you have written the server side code which is ready to accept data.
And, of course, I'm guessing that you wish to send data:{Student:Students} instead of data:{User:Users}. Preferably data:{Student:Students}
Please confirm the data type of "Students" object you are passign to controller.
Try to use Array data type,
Public ActionResult SendData(string id, string class,Array Students)
{
}
If it is not working then convert Javascript array to string array with delimeter(,) and use below
Public ActionResult SendData(string id, string class,string Students)
{
}
This will help you.
Thanks.

Categories