Javascript Success Function - javascript

i have this function in Javascript
function searchLoc() {
var a = document.getElementById('textL').value;
var lines = new Array();
lines.push(a);
$.ajax({
url: '/home/SearchLoc',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ 'lines': lines }),
contentType: 'application/json',
async: false,
cache: false,
success: function (result) {
window.location.replace("/OurBoxes");
}, error: function () {
alert("Chiamata fallita!!!");
}
});
}
This function call the function SearchLoc in the controller Home:
[HttpPost]
public bool SearchLoc(string[] lines)
{
string titolo = lines[1];
return true;
}
Both functions works well but when i return true, ajax execute the error statement and not the success funtion. Naturally i must to modify the controller, this is a test. Why if i return true it go on error.
Thanks to all

Your ajax function specifies that the return type is json, but your controller method returns bool. Change the method to return json
[HttpPost]
public bool JsonResult(string[] lines)
{
....
return Json(true);
}

Related

How to make Ajax call to method from controller

I have Controller PdfViewerController
inside of this controller I have a method
private static string GeneratePdfUrl(string test)
{
string aUrl;
//some action//
return aUrl
}
and I have pdfviewercontroller.js
inside or this js I want to crete a function that will return a string from Controller using GeneratePdfUrl()
something like this
function _doUrl() {
$.ajax({
type: "GET",
url: ep.utilities.replaceEPCommand('PdfViewer/GeneratePdfUrl'),
data: { "test": "R"}
});
}
what I'm doing wrong. Do I need something like .done ?
I try to create ajax Get function and expected to get string inside of my javascript
Assuming that you have an MVC Home controller
[HttpGet]
public JsonResult ForAjaxCall(string test)
{
var aUrl=GeneratePdfUrl(test);
return Json(person, JsonRequestBehavior.AllowGet);
}
This controller will call your custom method
public string GeneratePdfUrl(string test)
{
string aUrl;
//some action//
return aUrl
}
Inside your js file do something like :
function _doUrl() {
$.ajax({
type: "GET",
url: "/Home/ForAjaxCall",
data: { { "test": "R"} },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("You got your URL "+ response.aUrl);
},
failure: function (response) {
alert("Something wrong");
},
error: function (response) {
alert(response.responseText);
}
});
}
Hope this will help you understand the flow.

How to get a string from Controller and use it in view?

I'm trying to get some string from my Controller and use it in the View.
The ActionResult works like this:
public ActionResult GetSymbols()
{
string result = "SVG-String";
return Content(result);
}
This result is will be a svg-formatted string and should be shown in my svg-drawing, at the end.
I tried to call this controller-Action, using JavaScript and I could reach the Controller but how could I use the String? I couldn't see any result, so what is the rigth way to get the returned string into a variable?
The last try was like this:
$(document).ready(function () {
$.ajax({
url: "/Symbols/GetSymbols/",
method: "GET",
async: false,
data: "",
dataType: "string",
success: function (data) { alert(data); }
});
});
How about this one,
Change your Controller return type to Json
[HttpGet]
public JsonResult GetSymbols()
{
string result = "SVG-String";
return Json(result, JsonRequestBehavior.AllowGet);
}
And your javascript be like,
$(document).ready(function () {
$.ajax({
method: "GET",
url: "/Symbols/GetSymbols/",
async: false,
dataType: "json",
success: function (data) {
alert(data);
},
error: function (response) {
console.log(response);
}
});
});

Pass json from js to controller

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;
}

Jquery Ajax and MVC5 httpPost no value received

I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.

ajax postback does not work for byte array

I am trying to sent a byte[] in a postback action, but failed to get it.
Code snippets:
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: proxy.requestArgs,
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
While debugging, I can see byte[] in proxy.requestArgs.
But in the controller, I get null in this action result.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(byte[] param)
{
//I get null in this param.
}
Anything I am missing out?
Any Solution
You're passing data to the controller action and that action is expecting a post item named param. So in your JS, make your ajax call look like this (note the change to data):
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: { param: proxy.requestArgs },
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
Have you tried this?
Basically, accept the data as string in you action and inside it convert it into byte[]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string param)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(param);
}

Categories

Resources