I tried to start new view via parameter, but ajax post method couldn't pass parameter to the controller. Controller parameter always seen Null.
Index.schtml: I triggered in element in html also passing controller and action via Url.Action inside the element. Then run the script:
function getPList(target)
{
var Pdata = JSON.stringify({
'sNo': "88888888"
});
$ajax({
type: "POST",
dataType: 'json',
contentType: 'application/json',
url: target,
data: Pdata,
success: function (data) {
console.log("Response Data ↓");
console.log(data);
}
});
}
Controller:
public ActionResult PListIndex(String sNo)
{
return View(sNo);
}
How to pass controller parameter ?
Your controller variable is called sNo, but you are passing a variable in js called pNo. They should have the same name.
Also try to pass data like this:
$ajax({
type: "POST",
dataType: 'json',
contentType: 'application/json',
url: target,
data: { sNo: "888888" },
success: function (data) {
console.log("Response Data ↓");
console.log(data);
}
});
Related
In view I received model of type HistorySearch. Then I want to resend this model to controller using ajax:
$("#exportCsv").click(function () {
// get model as json
var searchData = '#Html.Raw(Json.Encode(#Model))';
searchData = JSON.stringify({ 'search': searchData });
$.ajax({
//contentType: 'application/json; charset=utf-8',
url: '#Url.Action("ExportToCsv", "BankCosts")',
type: 'POST',
data: searchData,
dataType: 'json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
async: true,
});
});
As you can see I had to comment contentType because for some reason with this passed model is set to null in controller.
Also, my controller is coded like this:
[HttpPost]
public void ExportToCsv(HistorySearch search)
{
// search properties are not filled. They are set to default value
}
The thing is binding is not working correctly. Received search properties are set to default values. Whats wrong there?
The JSON.stringify({ 'search': searchData }) will transform your object to string, so then will pass to your ActionResult a string instead of an object.
Remove the JSON.stringify and on ajax call change:
$.ajax({url: '...', ..., data: { searchData }, ...
This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].
Data doesn't passing to controller, always null
My script in view:
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { "json": JSON.stringify(selected) },
error: function () {
alert("Error!");
}
});
}
My home controller method:
[HttpPost]
public IActionResult DeleteRecords(string AllId)
{
return null;
}
send ajax request data like below,
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
and receive the data in action like
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}
It need to pass the action. Hope it helps to you.
with the code in your question, try below to get the json
System.Web.Context.Current.Request.Form["json"]
if you want some more graceful stuff, you need to put FromBody attribute in your parameter signature
DeleteResults([FromBody] string json)
Name your property in the Post the same as your method so that the automatic binding picks it up. - Turns out this doesn't matter for single object.
The data Object you were creating was not parse-able by .net, use JSON.stringify directly for the data payload.
Note: The change in Home controller since you are passing an array of string.
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
}
For your home controller method:
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}
i came across with a minor conflict while i am reading the html image value and passing value data in java script method works fine, and in ajax POST to pass the value towards controller, and unforunelty ajax point the controller over break point but the string Country parameter is null (passing a null value =), may i know the reason why please ! Thank you !
public ActionResult Prayer_Schedule(string Country){
}
<img src="~/images/flags/india.jpg" value="india" onclick="choose(this);">
<script type="text/javascript">
function choose(element) {
var Country = element.getAttribute("value");
$.ajax({
type: 'POST',
url: '../Home/Prayer_Schedule',
data: {
Country: Country,
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
timeout: 100000,
success: function (response) {
alert('ajax success: ' + response);
//location.href = "/thankyou.html";
}
});
You have to use jQuery.param for post
data: jQuery.param({ Country: Country}),
Or use $.post
$.post('../Home/Prayer_Schedule', { Country: Country },
You have set contentType: 'application/json; charset=utf-8' so you need to send json object or you can simply remove this to get value in controller.
$.ajax({
type: 'POST',
url: '../Home/Prayer_Schedule',
data: {
Country: Country,
},
dataType: 'json',
async: false,
cache: false,
timeout: 100000,
success: function (response) {
alert('ajax success: ' + response);
//location.href = "/thankyou.html";
}
});
Also if you have not decorated your method with HttpPost you will need this too.
[HttpPost]
public ActionResult Prayer_Schedule(string Country){
}
It may be your javascript on the getAttribute() function. You are using value, which isn't a valid attribute for an img tag. Try this instead, using data-* attributes:
<img src="~/images/flags/india.jpg" data-value="india" onclick="choose(this);">
then in your javascript:
element.getAttribute("data-value");
The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}