Get json datas from C# to javascript without using [WebMethod] - javascript

I have a C# Project, and a ASP.NET project (without database).
I want to call some methods from my C# Project, get the results in JSON and use it in my javascript without using the [WebMethod], I tried to make a Controller but I'm a little bit lost.
If you have any tips it would be nice, thank you.

The code in the controller should look like:
public class HomeController : Controller
{
[...]
public virtual ActionResult GetExample()
{
[...]
var result = ...;
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public virtual ActionResult Update(MyModel model)
{
[...]
var result = model
return Json(result);
}
[...]
}
And from your java script file you make an ajax call:
$.ajax({
url: "<path>/Home/GetExample",
type: "GET",
dataType: "json",
cache: false,
success: function (html) {
[...]
}
})
or:
$.ajax({
url: "<path>/Home/Update",
type: "POST",
dataType: "json",
data: $(#my-form).serialize(),
cache: false,
success: function (html) {
[...]
}
})

I don't have enough reputation so adding my comments here. You probably want to use Web Api here which is the reason you created controller. You probably need to refer Web Api site which will help you build controllers and expose interface to be called from javascript.
Web API

Related

how do i call web service from within a web service

i am really new to the REST world, or in fact the WebApp side of java, so please don't mind if it's a silly question.
I have a web page where pressing a button will call the following JS function:
function testFunction(){
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource",
type: 'get',
success: function (data) {
console.log(data)
}
});
});
}
where the above url is handled by my OWN web service(which is in java), that is the above GET will call the following Web Service:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}}
All i wanna do here is instead of returning "Got It", i wanna call another javascript function(dedicated to handle server kind of request) involving EXTERNAL rest call such as this:
function externalResource() {
$(document).ready(function() {
$.ajax({
url: "any_external_rest_call",
type: 'get',
dataType: 'json',
success: function (data) {
document.getElementById('demo').innerHTML = "Perfect"
}
});
});
}
where i wanna return the data from the externalResource function to getIt() to finally the testFuntion(), i know its possible, but couldn't find much of the details online. It would be really helpful if someone could clear this up to me.
You cannot call JavaScript code from your REST method in Java. However, you can use the ClientBuilder of the javax.ws.rs.client package.
Your method could look like this:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
client = ClientBuilder.newClient();
target = client.target("http://api.anotherRestService.com/details/")
return target.request(MediaType.APPLICATION_JSON)
.get();
}
}
This is just an example, I didn't try it in a real environment, but this is how you can do it. Now, you can call with your JS method testFunction the REST method of your Java backend. In you REST method getIt you call another rest service with the created client. The result of the second rest call is returned to your JS method testFunction.
Take a look at his: RestTemplate. This is Spring, however. Seeing as you are using JAX-RS maybe take a look at this: Jersey.
The flow you describe is not possible, it is however possible to chain several requests while using data from the response of the previous response:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource1",
type: 'get',
success: function (data) {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource2?id="+data.id,
type: 'get',
success: function (data) {
console.log(data)
}
});
}
});
});
If you wish to call another URL from your server, its a redirect call. Following would be an example server side code if you are using Spring framework.
#RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://www.google.com");
return redirectView;
}
As others have mentioned, you can also use Spring RestTemplate to do this.

404 Not Found calling Http Method from JavaScript in ASP

I've looked at a couple of threads now where they want to call a C# method from JavaScript in an ASP project. I can't figure out what I'm doing wrong. Here is my C# class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
namespace Selfservice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public String GetCredentials()
{
return User.Identity.Name.ToString();
}
}
}
And here is the JavaScript I'm trying to call:
window.onload = function () {
LiveSearch();
getCredentials();
//FetchAllUsers();
};
function getCredentials() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetCredentials", "Home")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf­8',
data: JSON.stringify(""),
success: function (cred) {
alert(cred);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
I keep getting a 404 Not Found status back. It's an ASP site that's deployed on an IIS, on one of my workplaces servers. We are using Windows Authentication, so I'd like to get the credentials of whoever is logged in and store it for something else later.
I'm kind of at my wits end here. Anyone got any ideas?
Have you just tried to reach "/Home/GetCredentials" as URL? Also like mentioned, change to GET method, remove the contentType and change dataType to "text" as your controller is not returning JSON.

Unable to reach controller ActionResult from javascript

EDIT 2
I was able to solve the problem. There was nothing wrong with the Javascript or Controller code. The problem came from a .dll file. In the controller method I build a new TextInfo object from the TextModel object. The TextInfo object comes from a .dll that's build from the API. This .dll however had multiple instances with different build dates in the File System. Seems like the old version wasn't removed properly but it was the one the compiler used. This created a 500 Internal Server Error telling me that a Method wasn't available.
EDIT 1
I'm fairly certain my problem stems from a property in my model not being set correctly but I'm not sure why. I had 1 instance where I was able to debug though furhter into the code but I'm clueless as to why or how that happened. Will update later once I find more answers.
I am having trouble accessing the controller action from my ajax call and it honestly makes no sense to me as to why I'm unable to start the code. The issue seems to be with the CurrentPageNumber. When I comment out this variable from both c# and javascript, I am able to hit the breakpoint in the controller. But when I uncomment that variable I can't hit the breakpoint. The error I'm getting is 500 Internal Server Error. To me that sounds like the JSON keys aren't the same as the Controller parameters, but as you can see below that isn't the case (unless if I turned blind). Any idea what the problem could be? Prehaps I'm looking in the wrong direction?
tl;dr Controller ActionResult not started when CurrentPageNumber is in the parameter and key list (uncommented), but it does start when it isn't (commented out).
I am trying to reach the following ActionResult.
public ActionResult SavePageInfo(List<TextModel> TextObjects, string ImageSource, int CurrentPageNumber)
I do this with the help of the following AJAX call
var json = JSON.stringify({ TextObjects: textObjects, ImageSource: imageSource, CurrentPageNumber: pageNumber });
$.ajax({
url: "/NextprintPhotobook/SavePageInfo",
type: "POST",
data: json,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log(data.message);
alert(data.message);
}
})
The JSON that's produced looks like this (as you can see all values are set):
"{"TextObjects":[{"text":"Test","x":50,"y":50,"fillColor":"#77DD44","fontFamily":"arial","fontStyle":"normal","fontSize":"18pt","fontWeight":"normal","textAlignment":"start","angle":0}],
"ImageSource":"http://localhost:22223/api/file/getfile?name=04.jpg&collectionId=4103&version=1&size=original",
"CurrentPageNumber":1}"
TextModel is as follows:
public class TextModel
{
public string text
{
get; set;
}
public int x
{
get; set;
}
public int y
{
get; set;
}
// Same properties as in the JSON.
}
Why are you not using a single object as parameter (a wrapper class for all those params)? (usually this is how it is done, unless you want to add some params in the query string also)
this is not the answer... well (i just want to put it here so its easier to read)
try this:
var data = {
TextObjects: JSON.stringify(textObjects),
ImageSource: imageSource
CurrentPageNumber: pageNumber
}
$.ajax({
url: "/NextprintPhotobook/SavePageInfo",
type: "POST",
data: data,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (res) {
console.log(res.message);
alert(res.message);
}
});

Posting to a controller in MVC4

I have asked a few questions here without any workable answers. I may have been on the wrong track or asked it all wrong. Basically, what I am trying to do is load up a VAR in the page:
var testModel = #Html.Raw(JSON.Encode(Model))
Then manipulate the testModel properties, which reflect the original model, with jQuery and JavaScript, then post it back to a controller method with an AJAX request:
$.ajax({
datatype: 'json',
data: testModel // ?? or some other way?
// etc
});
The controller:
public ActionResult PostModel (ModelName model) // or JsonResult
{
//do things
return Json(model); // or return View?
}
Any help would be appreciated.
I have tried what others have suggested below, and still the transaction never makes it to the controller method. Why not?
Ajax type Specifies the type of request. (GET or POST) DETAILS
$.ajax({
type: 'POST',//or GET
dataType: 'json',
data: testModel // ?? or some other way?
// etc
});
typerepresents the type of request you're making not the type of data you're going to get back. dataType is what you should have there and POST in the type field.
$.ajax({
type: 'POST',
dataType: 'json',
data: testModel // ?? or some other way?
// etc
});
Basically you are posting the data through javascript so on success you need a Json object to parse
so you need to return Json(model):
public ActionResult PostModel (ModelName model) // or JsonResult
{
//do things
return Json(model);
}
and your JS as:
$.ajax({
type: 'POST',
url: '{somecontroller}/{someaction}',
cache: false,
contentType: 'application/json; charset=utf-8',
data:testModel,
success: function (object) {
$.each(object, function (key, val) {
//do your stuff here
})
})
Where the key will be your Model Property name and val will be its value respectively
Now to remove your confusion "When to return View?"
There are three ways to pass information from a controller to a view in ASP.NET MVC. We use Html helpers to generate html fields and bind them with models to Get/Post the data values from view to controller
As a strongly typed model object. (for specific model)
As a dynamic type (using #model dynamic)
Using the ViewBag
Now when you are using the html helpers you can return view with the object model passed with it, which will automatically populate the data in your view as:
Strongly typed model object
<%# Page Title="#" Language="VB" MasterPageFile="#" Inherits="System.Web.Mvc.ViewPage(Of somemodel)" %>
Render view as
Return View("your View Path", modelObject)
Here's what I did to make this approach work:
In the page (.cshtml):
function SendJsonData() {
localModel.itemNumber = $("#txtItemNumber").val();
// etc for the rest of the fields
$.ajax({
url: '#Url.Action("PostModel", "ItemControl")',
data: JSON.stringify(localModel),
dataType: 'json',
cache: false,
type: 'POST',
contentType: 'application/json, charset=utf-8',
success: function(data) {
//do stuff
},
error: function () {
alert('error');
}
});
Then in the controller:
[HttpPost]
public JsonResult PostModel(ItemModel localModel)
{
//do stuff with data model
return Json(localModel);
}
This worked fine and seems to me to be the way to go for most applications using MVC4 and above. This way the entire model is in the page and can be readily manipulated with jQuery and JavaScript then sent to the controller for processing. This can even be a large complex model, I've tried it. No more post backs and page flicker and rewriting...

ASP.NET MVC - Render PartialView with AJAX?

Earlier today I posted another post where #Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);
isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);
and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
if (!ModelState.IsValid)
{
throw new HttpException(400, "Client-side validation failed.");
}
if (string.IsNullOrWhiteSpace(website.URL))
{
throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
}
using (_session.BeginTransaction())
{
_session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
_session.Transaction.Commit();
}
return PartialView(ListPartialView, MapUserToViewModel);
}
// MyJs.js
$("#testform").live('submit', function () {
var test = { URL: $("#URL").val() };
$.ajax({
url: "/Dashboard/AddWebsite",
type: "POST",
data: JSON.stringify(test),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("TRIG");
$("#content").html(data);
},
error: function () {
alert("Error");
}
});
return false;
});
Thanks in advance!
In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).
Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.

Categories