Accessing a controller method from javascript file(MVC3) - javascript

I have a method in the controller which returns a JASON output as given below.
public JsonResult GetJSONDateData()
{
JsonResult startDate = new JsonResult();
var Mystartdate = "02/01/2011";
startDate.Data = Mystartdate;
startDate.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return startDate;
}
And I try to access this method in javascript using
var query = '';
query = getDomainURL() + "/ControlelrName/GetJSONDateData";
jQuery.ajaxSetup({ async: false });
var startDate = ''; //The max size if nothing is coming from config...
$.post(query, function (response) {
startDate = response;
});
jQuery.ajaxSetup({ async: true });
IS there anything wrong in my functions? I am not getting anything in the response. Pls help
Thanks,
Adarsh

I suspect that you are making a GET request and it's not allowed.
In your action method try the following:
return JSON(startDate, JsonRequestBehavior.AllowGet);

Related

Display return data from external javascript

I'm trying to display the return data from the external Javascript.
Here's my code
global-functions.js
function CurrentDate() {
var url = CurrentDateUrl();
$.get(url, function (e) {
var Date = e.toString();
console.log(e);
console.log(Date);
return Date;
});
// RETURN the Current Date example. 11/29/2013 10:57:56 AM
}
Sample.cshtml (View)
<h2>Transaction Date: <b><span id="TransactionYear"></span></b></h2>
<script>
function CurrentDateUrl(){
return '#Url.Action("CurrentDate", "Global")';
}
$(document).ready(function () {
var Date = CurrentDate();
document.getElementById("TransactionYear").innerHTML = Date; // the return is UNDEFINED
});
</script>
As we can see in global-functions.js there is no problem as it return from what i wanted but when I try to call the function CurrentDate() it will return to UNDEFINED . Any other way to display it? or other good approach?
EDIT :
Question : Can you verify that function CurrentDate() is called?
Yes. As I try to return the hard coded string in CurrentDate() it will display.
I tried the suggested answer below
function CurrentDate() {
var url = CurrentDateUrl();
var result;
$.get(url, function (e) {
var date= e.toString();
console.log(e); // will return the Date in console
console.log(date); // will return the Date in console
result = date;
console.log(result); // will return the Date in console
});
console.log(result); // will return UNDEFINED in console
return "Sample";
}
OUTPUT
Transaction Date : Sample
I think you are using $.get() function in wrong way! Please see following link for more info. It cannot return value, it should execute callback function when request is finished!
You should pass function as callback in $.get() (which you are doing) and in that function do logic which you want (which you are NOT doing right now.)
I will rather do like this (probably not good in your case because you are using external file):
$.get(url, function (e) {
var Date = e.toString();
console.log(e);
console.log(Date);
document.getElementById("TransactionYear").innerHTML = Date
});
Or try this in your case (synchronous call):
function CurrentDate() {
var url = CurrentDateUrl();
var result;
$.ajax({
url: url,
type: 'get',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
Please note: I am using $.ajax() and I am not returning any value inside $.ajax. Also I added async: false. Now you can return result in that way but it is not async.
If you want to use asynchronous request you have to use callback function. Some implementation can be like in following example:
function CurrentDate(callbackFunction) {
var url = CurrentDateUrl();
var result;
$.get(url, function (e) {
var Date = e.toString();
callbackFunction(Date);
});
}
// Call your function in code like this
CurrentDate(function(result) {
// handle your result here
});

$http Call to Web API 2 Not Passing Parameter

This is my C# WebAPI2 controller, which gets hit:
[HttpGet, Route("bycaseidlist/{idArray}")]
public async Task<IHttpActionResult> GetByCaseIdList([FromUri] List<int> idArray)
This is the call:
var idArray = [4,4,2,4];
var url = baseUrl + 'api/cases/bycaseidlist/' + idArray ;
$http.get(url)
The problem is that the API doesn't get the array, it gets ...this:
In other words an array with one value: 0. Why is this happening? How do I fix it? It seems to be in-line with this answer, but it doesn't work. Should I pass it in the body? I feel like I am missing something obvious.
Get ActionMethods can take objects as arguments. However, the default behavior is to look at the body when the parameter is not a .net primitive. In order to force the action method to use a model binder to read the object data from the request, the parameter can be decorated with the [FromUri] or [ModelBinder] attributes. (Note there are other ways to do this that include doing parameter binding rules but that is probably overkill for what you are trying to accomplish here). Here is an implementation that solves the original problem that you were posing.
<script type="text/javascript">
var ajaxCall = function (myArry) {
var ajaxProperties = {};
ajaxProperties.url = "/api/Mul/Mutiply";
ajaxProperties.type = "Get";
ajaxProperties.data = {};
ajaxProperties.data.numbers = myArry;
ajaxProperties.contentType = "application/json";
console.log(ajaxProperties);
ajaxProperties.success = function (data) {
console.log(data);
}
ajaxProperties.error = function (jqXHR) {
console.log(jqXHR);
};
$.ajax(ajaxProperties);
};
var getData = function (e) {
var myArry = new Array();
myArry.push($('input[name=num1').val());
myArry.push($('input[name=num2').val());
ajaxCall(myArry);
return false;
};
</script>
Controller
[HttpGet]
public IHttpActionResult Multiply([FromUri] int[] numbers)
{
int result = 0;
if(numbers.Length > 0)
{
result = 1;
foreach (int i in numbers)
{
result = result * i;
}
}
return Ok(result);
}
}
I think my mistake was using Get. I might be remembering incorrectly (someone confirm if you know offhand), but Get might not be able to take objects as arguments. Anyway, I changed the method to POST and then changed the param to be sent in the request body, rather than the url. It now works. Here is the working code:
[HttpPost, Route("bycaseidlist")]
public async Task<IHttpActionResult> PostByCaseIdList([FromBody] int[] sqlCaseIdArray)
and the call itself:
function runDbCall(url, sqlCaseIdArray){
return $http({
method: 'POST',
url: url,
data: sqlCaseIdArray
});
}
runDbCall(url, sqlCaseIdArray)
I will come back to this when I figure out if the problem was Get not being able to take objects, but I thought it could in url, just not in body...need to clarify. If someone posts an answer just on that part, I will accept, since that's probably the root of the prob.

Get return value from Controller to javascript

What I want is, I want to check whether there is a file in the database or not. To do this I have a method in the controller which checks this and returns a boolean for the corresponding case. It looks like this:
public bool fileInDb(int empId)
{
using (SLADbContext db = new SLADbContext())
{
bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
if (file)
{
return true;
}
else
{
return false;
}
}
}
I simply just check if there is any file assigned to the given employee.
Now I would like to call this method from my javascript in the view, and get the return value, so that I can let the user know, if there is a file assigned to the selected employee or not. It may look like this:
$("#get-file").click(function() {
empId: $("#EmployeeSelect").val();
var fileInDb = // Get the return value from the method 'fileInDb'
if(fileInDb) {
// Let the user download the file he/she requested
var url = "#Url.Action("GetUploadedFile", "Competence")";
this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
} else {
alert("There is no file assigned to this employee.");
}
});
So my question now is, how do I get the get the return value from the method in the controller?
I would suggest few changes here:
Change your controller method to have return type ActionResult or JsonResult and I prefer JsonResult would be enough here and retrun Json response from controller and manipulate this method with $.get. You also need to change parameter to string because the parameter will be received as Json string.
public JsonResult fileInDb(string eId) //change signature to string and then convert to int
{
int empId=Convert.ToInt32(eId);
using (SLADbContext db = new SLADbContext())
{
bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
if (file)
{
return Json(new { result = true },JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { result = false},JsonRequestBehavior.AllowGet);
}
}
}
Now your ajax-get call would be as below:
$("#get-file").click(function() {
var eId= $("#EmployeeSelect").val();
$.get('/YourControllerName/fileInDb',{'eId':eId},function(response){
//you just need to get the response so $.get is enough to manipulate
//this will be called once you get the response from controller, typically a callback
if(response.result) //same result variable we are returning from controller.
{
// Let the user download the file he/she requested
var url = "#Url.Action("GetUploadedFile", "Competence")";
this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
} else {
alert("There is no file assigned to this employee.");
}
})
});
You need to set-up a single page script using your ASP fileInDb function and then communicate with that page using AJAX from the browser. If you're unfamiliar with AJAX I'd recommend using the jQuery implementation to get you started.
You can use jquery and ajax to achieve this. Call your method using an ajax call from your client code. Here is an example as a reference :Calling controller method from view
In the backend create a method to call, returning a JsonResult
public JsonResult fileInDb(int empId)
{
// your code - set fileExists to true/false
JsonResult returnObj = new JsonResult
{
Data = new
{
FileExists = fileExists ;
}
};
return Json(returnObj);
}
in your javascript code use $.ajax
$.ajax({
cache: false,
url: '#Url.Action("fileInDb")',
data: { 'empId': someVar },
type: 'POST',
success: function (response) {
if (response.Data.FileExists === true) {
// do something
} else {
// it was false
}
},
error: function (er) {
alert('Error!' + er);
}
});

Succesfull $.Ajax and $.Post calls always return failure from C#

I need a cross domain web api method to return valid jsonp to some javascript from C#. I can't seem to make this magic happen. I've looked around the web and can't find a start to end example that fits my needs and works... Fiddler shows that I'm returning valid json data but when I hit a breakpoint in F12 dev tools or firebug the result is a failure message.
Here is what I've currently got:
C#
/// <summary>
/// POST: /Instance/RefreshItem
/// </summary>
/// <param name="instanceId"></param>
/// <returns>Json</returns>
[HttpPost]
public System.Web.Mvc.JsonResult RefreshItem(int instanceId, Guid customerId)
{
try
{
var clientConnection = Manager.ValidateInstance(customerId, instanceId);
clientConnection.RefreshItem();
var result = new MethodResult()
{
Success = true,
Value = instanceId,
Message = "Item successfully refreshed."
};
return new System.Web.Mvc.JsonResult() { Data = result };
}
catch (Exception ex)
{
Manager.LogException(_logger, ex, customerId, instanceId);
var result = new MethodResult()
{
Success = false,
Value = instanceId,
Message = ex.GetBaseException().Message
};
return new System.Web.Mvc.JsonResult() { Data = result };
}
}
JS
Example.RefreshItem = function ()
{
Example.SDK.JQuery.getSettings(
function (settings, userId, userLocaleId)
{
alert("Attempting to refresh item for instance " + settings.ConnectionId + "\r\nThis may take awhile.");
var url = settings.SystemUrl + "/Api/WebApiServices/ExampleAdmin/RefreshItem?customerId=" + settings.CustomerId + "&instanceId=" + settings.ConnectionId;
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'RefreshItemCallback',
success: RefreshItemCallback
})
},
Example.SDK.JQuery.defaultErrorCallback
);
}
function RefreshItemCallback(data)
{
alert(data.d.Message);
}
I've also tried $.Post().Always() with the same results.
What am I doing wrong???
I think your problem is that you're instantiating a JsonResult instead of using the Json method.
Presumably the C# method you have is in a controller, so instead of
return new System.Web.Mvc.JsonResult() { Data = result };
do:
return Json(result);
This method probably sets some of the other properties of the JsonResult that, when not set, will not be properly received by the client.
See how Microsoft only shows you how to create a JsonResult via the Json method on MSDN
Note that the same is probably true with methods like View, Content, and File.
Fight all week unable to find an answer until you ask the question somewhere... Within 30 minutes of asking I found this: http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/ which was exactly what I needed.
Thanks to all who posted.

How to call server side function from json?

this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.

Categories