Is there c# code that takes an existing controller, analyse its public Action methods and generate a JavaScript proxy class so that it can be easily called by other Javascript code? I already know we can use jquery to do a $.post and $.get to call our ajax services but I believe the process can be simplified by not having to specify the relative url of the AJAX web service URL and a parameter name for each parameter input.
For example, let's say we have the following C# controller:
public class CustomerController : Controller
{
public JsonResult Create(string name, string address)
{
return new JsonResult {Data = 11111};
}
public JsonResult Update(int id, string name, string address)
{
return new JsonResult {Data = true};
}
}
I would like to call the controller's AJAX action methods by using the following fashion.
Proxy.Customer.Create("Scott Gu", "Somewhere in Redmond").done(function(id) {
/* id is an int and not an string */
Proxy.Customer.Update(id, "Scott Gu", "Somewhere in Seattle");
});
Does a project exist that allow me to do this?
Update
it turns out there's no project that does what I asked for. Something that could be of use, besides SignalR, is Phil Haack's Controller Inspector project. It can inspect any given controller and reveal what action method it has, the parameters it accepts, their types, etc.
The following link contains the getter method for retrieving a details about a given controller. https://github.com/Haacked/CodeHaacks/blob/master/src/MvcHaack.ControllerInspector/ControllerDetailer.cs
Update 2
Doh. Phil Haack already developed a JavaScript proxy. Tutorial can be found here.
JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.
Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.
async actions help best when the actions does some I\O operations to DB or some network bound calls where the thread that processes the request will be stalled before it gets answer from the DB or network bound call which you just invoked.
Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view.
I know, it's an old question, but I just found a project which seems to match your requirements:
ProxyApi by Steve Greatrex
http://blog.greatrexpectations.com/2012/11/06/proxyapi-automatic-javascript-proxies-for-webapi-and-mvc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With