Javascript-AJAX call
function assignTask(){
var formdata = "xyz";
var taskList = [];
$.each($("input[name='taskname']:checked"), function(){
taskList.push($(this).val());
});
$.ajax({
type: "post",
data: {taskList:taskList},
url: "AssignTask" ,
traditional: true,
success: function (data)
{
........}
});
}
Now var taskList is storing array successfully. Since i have checked that already.
The problem happens inside the AJAX function while sending the array taskList.
struts.xml
<struts>
<constant name="struts.custom.i18n.resources" value="ApplicationResources"/>
<package name="default" extends="struts-default" >
<action name="AssignTask" class="dto.Task" method="assignTasks">
<result name="success">jsp/TaskList.jsp</result>
</action>
</package>
</struts>
dto.Task java class with method assignTasks()
public class Task extends ActionSupport {
private ArrayList<Task> taskList;
public ArrayList<Task> getTaskList() {
return taskList;}
public void setTaskList(ArrayList<Task> taskList) {
this.taskList = taskList;
}
public String assignTasks() {
System.out.println("Inside assign tasks..."+ taskList.size());
String result = "success";
return result;
}
}
When I am running the application in Netbeans, glassfish console is showing me this error:
Warning: Could not find action or result
No result defined for action dto.Task and result input
at at com.opensymphony.xwork2.DefaultActionInvocation......
......
Google Chrome console is showing me this error:
jquery.min.js:4 POST http://localhost:8080/EmployeeManagement/AssignTask 404
(No result defined for action dto.Task and result input)
So my program's control is not going inside the function assignTasks() and of course there is a problem in passing array from AJAX function to the dto.Task java class via struts2 framework.
Please help me solve it.
Could you try adding namespace attribute as below?
<package name="default" extends="struts-default" namespace="/">
...
</package>
Related
I am sending Json data but when I verify my method in my controller it arrives as null
html:
<div class="hijo">
#Html.LabelFor(m => m.Proyecto, new { #class = "", style = "color:#040404" })
#Html.DropDownListFor(Model => Model.ProyectoID, Model.Proyecto, "Seleccionar")
#Html.ValidationMessageFor(Model => Model.Proyecto, null, new { #class = "label label-danger", id = "Proyecto" })
</div>
<div class="hijo">
<input type="button" id="adicionar" value="Agregar" class="myButton">
</div>
JS:
$('#adicionar').click(function () {
debugger;
var data= {
Proyecto: $("#ProyectoID option:selected").text()
};
$.ajax({
url: "../ManejoDatos",
type: "POST",
dataType: "json",
data: JSON.stringify(data),
success: function (mydata) {
$("#UpdateDiv").html(mydata);
history.pushState('', 'New URL: ' + href, href); // This Code lets you to change url howyouwant
}
});
}
My Controller
public JsonResult ManejoDatos(string Proyecto)
{
........
...
return Json(Proyecto);
}
Console
I don't know if it's something very simple to fix but I don't see the error
regards
I found your JavaScript code is absolutely fine. The weird things is controller with your format ghostly doesn't work But I got success below way:
[System.Web.Http.HttpPost]
public HttpResponseMessage ManejoDatos(string Proyecto)
{
var data = " my test data ";
return Request.CreateResponse(HttpStatusCode.OK, data);
}
I will investigate that obviously and update the answer again .
Hope above idea help you to resolve your problem. Let me know if you encounter any more problem.
Simple types like string,int,float etc are to be fetched from query string in .Net framework where as complex types always fetched from body.
Solution-1
In this case .Net Framework is expecting string Proyecto from query parameters and you can call your API like this without making any change to your server side code
Note:Also you don't need to define key of the parameter (in http request) which is being defined as [From Body]. As total of one simple type can be passed using [FromBody] attribute which you can see below like this =ProyectoValue
POST ../ManejoDatos HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded
=ProyectoValue
Solution-2
Or you can call your API by putting all your params in complex model and pass params through body instead of query parameters like this
Complex Type Model
public class MyModel
{
public string Proyecto{ get; set; }
}
API Code
public JsonResult ManejoDatos(MyModel myModel)
{
//Access using mymodel.Proyecto
........
...
return Json(mymodel.Proyecto);
}
And now you can consume your API by passing paramters through body like this
POST ../ManejoDatos HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded
proyecto=myproyecto
I want to call CsharpFunction, a C# function in code-behind, from JavaScript. I tried the code below but whether the JavaScript condition is True or False, CsharpFunction was called regardless!
JavaScript code:
if (Javascriptcondition > 0) {
<%CsharpFunction();%>
}
C# code behind:
protected void CsharpFunction()
{
// Notification.show();
}
How do I call a C# function from JavaScript?
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
.CS File
namespace Csharp
{
public void CsharpFunction()
{
//Code;
}
}
JS code:
function JSFunction() {
<%#ProjectName.Csharp.CsharpFunction()%> ;
}
Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name
A modern approach is to use ASP.NET Web API 2 (server-side) with jQuery Ajax (client-side).
Like page methods and ASMX web methods, Web API allows you to write C# code in ASP.NET which can be called from a browser or from anywhere, really!
Here is an example Web API controller, which exposes API methods allowing clients to retrieve details about 1 or all products (in the real world, products would likely be loaded from a database):
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
[Route("api/products")]
[HttpGet]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
[Route("api/product/{id}")]
[HttpGet]
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
The controller uses this example model class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Example jQuery Ajax call to get and iterate over a list of products:
$(document).ready(function () {
// Send an AJAX request
$.getJSON("/api/products")
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});
Not only does this allow you to easily create a modern Web API, you can if you need to get really professional and document it too, using ASP.NET Web API Help Pages and/or Swashbuckle.
Web API can be retro-fitted (added) to an existing ASP.NET Web Forms project. In that case you will need to add routing instructions into the Application_Start method in the file Global.asax:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Documentation
Tutorial: Getting Started with ASP.NET Web API 2 (C#)
Tutorial for those with legacy sites: Using Web API with ASP.NET Web Forms
MSDN: ASP.NET Web API 2
Use Blazor
http://learn-blazor.com/architecture/interop/
Here's the C#:
namespace BlazorDemo.Client
{
public static class MyCSharpFunctions
{
public static void CsharpFunction()
{
// Notification.show();
}
}
}
Then the Javascript:
const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
Blazor.platform.callMethod(CsharpFunction, null)
}
Server-side functions are on the server-side, client-side functions reside on the client.
What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.
More info can be found here
and here
If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.
You can't. Javascript runs client side, C# runs server side.
In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.
To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.
I am currently struggling with an error that appears in my Chrome developer tools console
GET http://localhost:8080/movie_db/search/movie?movieTitle=Machete 415 (Unsupported Media Type)
when I try to connect to my REST service with angular JS. Since I had this issue before when I tried to access the REST service via a Simple REST plugin in Chrome, I assume that most likely a missing Content-Type header parameter is the reason for that (should be Content-Type: 'application/json').
Angular JS website says, that one could set header parameters as follows: $httpProvider.defaults.headers.get['My-Header']='value'. Regretfully this didn't have any impact and the problem still exists.
Thus I'd like to know how I can manipulate the header parameters with angular JS that are sent over to my REST service.
Right at the moment, my code looks like this:
function SearchMovieController($scope, $resource) {
$scope.SearchMovie = $resource('http://localhost\\:8080/movie_db/search/:action',
{action: 'movie', movieTitle: 'Machete'},
{get: {method: 'JSONP', headers: [{'Content-Type': 'application/json'}, {'Accept' : 'application/json'}]}});
$scope.SearchMovie.get()
}
Server side looks as follows (I use Spring MVC):
CONTROLLER:
#Controller
#RequestMapping( "/search/movie" )
public class SearchController { // TODO rename?
private final TheMovieDBService theMovieDBService;
#Autowired
public SearchController( TheMovieDBService theMovieDBService ) {
this.theMovieDBService = theMovieDBService;
}
#ResponseBody
#RequestMapping( method = RequestMethod.GET, produces = "application/json", consumes = "application/json" )
public Map<String, Object> search( #RequestParam String movieTitle ) {
Map<String, Object> response = new HashMap<String, Object>();
try {
TheMovieDBSearchResult searchResult = theMovieDBService.searchMovie( movieTitle );
response.put( "result", searchResult );
response.put( "success", "true" );
} catch ( EncoderException e ) {
response.put( "success", "false" );
}
return response;
}
}
web.xml
<servlet>
<servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.u6f6o.apps.movie_db.config.web.ServletConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I had to step through all of Angular's $httpBackend stuff just recently, and JSONP uses a different method to load data than the other requests.
EDIT: The code in question
So if you specify jsonp has your method it is using the following method to load your data. This will, of course, completely ignore any headers you set yourself.
in $httpBackend:
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
}
I'm porting an ASP.net Web Forms application to MVC.
The application uses AJAX, by means of Ajax-enabled WCF Web service and asp:ScriptManager. I send an array of objects for service, it handles it just great. Code example,
<script type="text/javascript">
$().ready(function () {
var ser = new Services.TasksService();
$('#tasks').tasksgrid(
'newTaskName',
'createTask',
'submitData',
loadData,
submitData,
deleteData
);
function loadData(callback) {
return ser.GetAllTasks(callback, null, null);
}
function submitData(data, callback) {
return ser.Submit(data, callback, null, null);
}
function deleteData(data, callback) {
return ser.Delete(data, callback, null, null);
}
}
);
</script>
WCF service side code:
[ServiceContract(Namespace = "Services")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TasksService
{
[OperationContract]
public IList<Task> GetAllTasks()
{
//Code..
}
[OperationContract]
public void Submit(IList<Task> tasks)
{
//Code..
}
[OperationContract]
public void Delete(IList<Task> tasks)
{
//Code..
}
}
The Submit/Delete method, recieves Array of Tasks objects. I create those array dynamically in client side script and just put it to corresponding Services.TasksService (no $.toJSON or JSON.stringly call, nothing like that). WCF infrastucture handles it greacefully and I always get a correct object on server.
Now, I'm getting rid of WCF service and try to do the same with Controller class. GetAllTasks were fine.. but I totally missed with 'recieving' data methods.
In controller I have,
[HttpPost]
public JsonResult Submit(IList<Task> tasks)
{
On client,
function submitData(data, callback) {
$.post('/Tasks/Submit', JSON.stringify(data), callback, 'json');
}
But anything I tried, I always recieve null as tasks object (so, data is not binded).
I've seen Phil Haack post on that, but would like to avoid using of any additional assemblies, if possible.
MVC needs to be told what variable on the server side to bind the data to. In your example you could do the following:
function submitData(data, callback) {
$.post('/Tasks/Submit', { tasks: data }, callback, 'json');
}
Look here http://theycallmemrjames.blogspot.com/2010/05/aspnet-mvc-and-jquery-part-4-advanced.html
I need to make a post ajax request, where in i need to pass entity classes as parameter.
for eg:
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json
)]
public bool SaveEmployee(Employee employee)
{
//inserting the data to database.
}
here my entity class is Employee which has 2,3 properties exposed, say empId,employeename and age.
These informations i need to pass from javascript.
function SaveEmployee() {
var employeename='test';
var age=23;
var empid=34534;
//these data's i need to pass to the ajax method.
var am = new Proxy();
am.invoke("SaveEmployee", { **here how can i pass my entity Employee?** }, function(response){
if (response) {
can i do something like this in the javascript?
var employee=new Employee();
employee.Name=employeename;
employee.Age=age;
employee.EmpId=empid;
and am.invoke("SaveEmployee", { "Employee":employee },
Here's a sample I put together that POSTs an entity to a WCF REST service (using jQuery on the client side). If you're not using jQuery, I think you'll still see how to handle it.
Here's the HTML & JavaScript:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
Name: <input type="text" id="name" /><br />
Desc: <input type="text" id="desc" /><br />
<button id="submit">Send!</button>
<script type="text/javascript">
$(function () {
$("#submit").click(function (e) {
e.preventDefault();
var theData = {};
theData["Name"] = $("#name").val();
theData["Desc"] = $("#desc").val();
$.ajax({
type: "POST",
url: "ProdService.svc/product/add",
data: JSON.stringify(theData),
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (e, t, x) {
alert(t);
}
});
});
});
</script>
</body>
</html>
The key things to note is that I'm setting the content type of the request to application/json. That's key for WCF so it knows what's being sent up.
My service is defined as such:
[OperationContract]
[WebInvoke(Method="POST", ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json,
BodyStyle=WebMessageBodyStyle.Bare, UriTemplate="product/add")]
String AddProduct(Product p)
{
return "Got " + p.Name;
}
And my entity is like this:
[DataContract]
public class Product
{
[DataMember()]
public String Name { get; set; }
[DataMember()]
public String Desc { get; set; }
}
My web.config is set up like this:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication2.ProdServiceAspNetAjaxBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WebApplication2.ProdService">
<endpoint address="" behaviorConfiguration="WebApplication2.ProdServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WebApplication2.ProdService" />
</service>
</services>
</system.serviceModel>
The key in the web.config is that my endpointBehavior uses webHttp instead of enableWebScript. Other than that, this is pretty much an out-of-the-box configuration.
So the keys are that my payload is a JavaScript object literal converted to a JSON-ized string. My service is expecting the request format to be JSON, and since my Product class is decorated with the DataMember and DataContract attributes, it can deserialize my payload to a Product class instance.
I hope this helps. Please let me know if you have other questions and I'll update my answer accordingly.