ASP.net MVC put complex data (array) to controller method - javascript

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

Related

Handing C# .NET events with edge.js in Node.js for electron

I need to do some calls from my js to my C# DLL in my Electron project and it works fine in this way:
c#
namespace Electron.Wrapper
{
public class QueryWrapper
{
public async Task<object> OnQuery(dynamic request)
{
...
return ..;
}
}
}
js
let edge = require('electron-edge-js');
let queryWrapperQuery = edge.func({
assemblyFile: '..dllUrl..',
typeName: 'Electron.Wrapper.QueryWrapper',
methodName: 'OnQuery'
});
window.query = function (options) {
queryWrapperQuery(JSON.stringify(options), function (error, result) {
...
});
}
The problem is that I use an external DLL that triggers async events sometimes, so I need find a way for listening the .NET events from js.
I found this way for resolve my problem but I think isn't the right way because I need a class library for Electron and I don't know how use it with also the previous way and probabily I don't need a WebSocketServer.
A .Net and js sample will be valued.
Thanks,
Andrea
Update 1
I found this way, cold be the right one? I'm trying to implement .net, any suggestions?
I found a good way:
C#:
public Task<object> WithCallback(IDictionary<string, object> payload)
{
Func<object, Task<object>> changed = (Func<object, Task<object>>)payload["changed"];
return Task.Run(async () => await OnQuery(payload["request"], changed));
}
js:
var withCallback = edge.func({
assemblyFile: '..dllUrl..',
typeName: 'Electron.Wrapper.QueryWrapper',
methodName: 'WithCallback'
});
window.query = function (options) {
function triggerResponse(error, result) {
...
}
withCallback({
changed: (result) => triggerResponse(null, result),
request: JSON.stringify(options)
}, triggerResponse);
};
When you need trigger when someting changes you should use the parameter 'payload' in OnQuery function:
public async Task<object> OnQuery(dynamic request, dynamic payload = null)
{
...
}
Next the OnQuery return the value you can call again the js callback in this way:
payload("Notify js callback!");
I hope this can help someone!

Angularjs, JavaEE and http request with inherited objects?

I work on webapp and can't find solution or example of my problem.
I use AngularJS, RestServis and JavaEE . My problem is how to send inherited object with superObject
In java I have two classes:
public class User{
protected String userName;
protected String userSurename;
..
..
}
Second class is a subclass
public class Worker extends User{
protected int idWorker;
protected String position;
..
..
}
in Angular controller I have
$scope.user = {
userName : "jon" ,
userSurename :"dep" }
$scope.worker= {
idWorker: 88 ,
position: "seller" }
and I use http protocol to send data on server side like this
this.saveWorker = function(worker) {
return $http({
method:'post',
url:this.apiBasicUrl,
contentType: "application/json",
data: worker
});
};
How in Angular in data to put one object and on Java side get worker object with user data also ? Can I , object like in java , make in angular with inherited ?
On Angular side, I suggest using $resource for communication with REST API:
var Worker = $resource('/worker/:workerId', {workerId:'#id'});
//get
var worker = Worker.get({workerId:123}, function() {
worker.abc = true;
//save
worker.$save();
});
On server side you should have a REST endpoint that is supposed to pick up these objects:
#Path("/worker")
public class WorkerService {
#GET
#Path("{workerId}")
public Worker getWorker(#PathParm("workerId") Integer workerId) {
//implement
}
#POST
public void saveWorker(Worker worker) {
//implement
}
}
This might not work out of the box. You will most likely need Jackson provider to enable REST to "translate" JSON into Java objects.
See this example: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

ASP.NET MVC 3 routes with backbone views

I'm pretty new to the web and am trying to understand what happens on our current project. For one of our single page apps, the Controller returns a single view for the whole area.
[HttpGet]
[Url("admin")]
public virtual ActionResult Index()
{
return View(Admin);
}
In the actual Admin.cshtml, we create a backbone router that gets initialized for that section of the page and has the different views for that single page app section. My question is, I want to create an action on the route
admin/import/upload
How would that look? I don't want to actually return a View, but I want to call a function when that route gets hit to validate the uploaded file and return JSON info about the file.
You need to define a model that has a property for your uploaded file like so, it should be of type HttpPostedFileBase.
public class UploadModel
{
[Required(ErrorMessage="Please choose a file to upload.")]
public HttpPostedFileBase Photo { get; set; }
}
Then you need to make your action that accepts the specified model and returns JavaScript instead of View.
public ActionResult Upload(UploadModel model)
{
//only continue if the model is valid (i.e. all the required fields have been set)
if (ModelState.IsValid)
{
string json = "";//build your JSON here
//return the JSON as a javascript response (with the correct headers, etc)
return JavaScript(json);
}
return View(model);
}
(function() {
window.App = {
Router: {}
View: {}
};
App.Router = Backbone.Router.extend({
routes: {
'*AreaName/admin/import/upload': 'upload'
},
upload: function() {
var upload= new App.View.upload();
},
});
$(document).ready(function() {
window.routes = new App.Router;
Backbone.history.start({ pushState: true });
});
})();

How to call a C# function from JavaScript?

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.

Invalid web service call, missing value for parameter with Backbone and Webservice webmethods

Is it possible for backbone to interface with asp.net soap webservice methods for saving and retrieving the data? because i got this error from the webmethod but actually the POST contains the parameters.
Server Side
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Dummy SaveDummy(Dummy myDummy)
{
Dummy dumdum = myDummy;
HttpContext.Current.Session["data"] = dumdum;
return myDummy;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static Dummy FetchDummy()
{
return (Dummy)HttpContext.Current.Session["data"];
}
public class Dummy
{
private string _name;
private string _script;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Script
{
get
{
return _script;
}
set { _script = value; }
}
}
Backbone Model
window["model"] = Backbone.Model.extend({
initialize: function () {
console.log("CREATED");
},
defaults:{
name:"Please enter your name",
script:"Hello World"
},
urlRoot: "index.aspx/SaveDummy",
validate: function (attrs) {
}
});
Application
$("document").ready(function () {
var myModel = new model({
name: "Stack Overflow",
script: "alert('Hi SO')"
});
var myView = new view({
model: myModel,
el: $("#placeholder")
});
console.log("SAVING");
myModel.save();
console.log("FETCHING");
myModel.fetch();
POST
{"name":"Stack Overflow","script":"alert('Hi SO')"}
Message
Invalid web service call, missing value for parameter: 'myDummy'.
Note
I did look into other posts with similar problem, which were solved by doing something like
{myDummy={"name":"Stack Overflow","script":"alert('Hi SO')"}} . How could this be generated using Backbone?
All of the server-side synchronization in Backbone is handled through Backbone.Sync which is designed for two things:
REST apis that work with JSON (not SOAP/XML)
Extensibility
So you will need to override the Backbone.Sync behavior to talk to your backend. It appears to be relatively straight-forward. Some guidance can be found in these links:
SO post about overriding Backbone.Sync
Blog post about consuming XML services in Backbone

Categories

Resources