I am working with asp.net mvc4. I have an action method which is a get method as it returns a an mvc view that is called from JavaScript/Jquery.
The javascript makes a get request to the controller action. I have a json object that I would like to pass to the mvc action. But as its a get request, as I need to return a view from it, it is posing difficult.
Is it possible to pass a json object that maps to an object on the signature of the controller action? I was looking libraries that may help such as http://benalman.com/projects/jquery-bbq-plugin/
Any tips or ideas?
You dont need any external APIs to do that. All you need to do is make an c# object with the same property and name as the JSON Object.
For E.g. Create an Object as
public class MyObject{
public string MyProperty1{get; set;}
public string Property2{get; set;}
}
And creating object in the jquery is all correct i assume and use jquery syntax like
as below
$.get('#Url.Action("MyAction","MyController")',
{myObject: jqueryObject},
function(resp){$("#myDiv").innerHTML(resp);});
And in case of Action use function declaration like
public ActionResult MyAction(MyObject myObject)
{
// your code here
return PartialView("_MyPartialView", myModelForPartialView);
}
BTW this way works for both Get and Post.
you could use something like servicestack http://www.servicestack.net/ this takes care of everything, and does it very well, as an alternative there is the MVC API options, but servicestack is better at this.
I am sure if you look at this project, you will either get great ideas from it, or learn to decouple your data driven code, away from your UI project.
Related
I am trying to understand decorators which are not java's annotations but more like pre-processors in this article and I also found this SO question on setting info on a function. Let's say I have an interface like so
export default interface UserService {
#Path("/users/create")
#POST
createUser(user: CreateUserRequest): Promise<CreateUserResponse>;
#Path("/users/delete")
#POST
deleteUser(user: DeleteUserRequest): Promise<DeleteUserResponse>;
}
sidenote: It would be great to use this generated client in react UI as well as use in nodejs
I want my #Path and #POST, #GET to save info I can read and I think
class Path(path:string):
def __init__(self, path):
self.path = path
def __call__(self, func):
func.pathAnnotation = self
return func
I read I cannot loop over methods in an interface yet I would like to generate the http client that implements this interface so any API developers create, it automatically creates the implementation. (In java, we use the Proxy.java to generate an implementation). On server side, the controller implements the same exact API and I like to generate the 'scaffolding' meaning the http request to which endpoint to call if possible (not sure I can do that in nodejs just yet).
EDIT: An idea: Perhaps, I create an abstract class or class and every method throws an exception "Use XXXFactory to generate the implementation of this class". How do I loop over method in that class? and can I create classes that extend all these 'apis' at runtime such that I can inject him for everyone to use(like Proxy.java in java world)?
EDIT: perhaps I could do this in javascript with a prototype class somehow... generate all the methods to call a method with signature
Promise<Object> invoke(String method, object[] paramsToMethod);
Then, I can look up the method and #Path and #GET/#POST properties on that method. Can a prototype class extend a class in javascript such that any api defined (perhaps defined in typescript) is implemented by this one class? Then I have every api implemented by the same code for every microservice like we do in java? (This then means the platform team can swap protocols and developers do not care about protocols anymore like http, http2, binary, etc)
As per request, I have took some time to tinker around with reflection. The reflection is mostly needed to make the client automatically conform to what the service expects (type of parameters/return type), and I think it might be possible with reflect-metadata.
Ok so the idea is to have decorators store metadata about the method in a map, where a key is the class and the value is a collection of the methods with metadata.
Then where you get the client, it aggregates all the metadata for each method into one function that can be used.
It's a vague start but I think it can work. I actually might also turn this into a small snippet or library too if I have the time.
But actually, this should be a statically generated client, not a dynamic one. Because then it is far easier to validate and do the code generation.
Playground
I'm trying to use a javascript var in the bean variable. This variable is the index that I need to get all values from my object. But it doesn't recognize, how can I do this? Or can you help me with an alternative solution. Thanks.
function cargarCategorias() {
while ( indice <= 5){
var valor = "#{ctrDashboard.objReporte1.get(indice)[0]}";
categorias.push(valor);
}
}
You seem to misunderstand that Java code (ctrDashboard.getObjReporte1.get(indice)[0]) operates on the server machine and JavaScript code (function cargarCategorias() { ... }) operates on the client machine within the context of webbrowser. Thus, you can't directly use these two languages interchangingly. But still, understanding lifecycle of JSF framework will help you achieve your goal.
So, your problem can be solved by using different tools. For example, if you want to preload a set of data to a JS context upon initial GET request on the page, you need to have an array of elements in JS while the page is being rendered:
<script type="text/javascript">
var valors = #{bean.valorsJson};
</script>
with bean method as:
public String getValorsJson() {
return new Gson.toJson(valorList);
}
I proposed to use Gson library for the purpose, but you're free to choose a way of creating JSON object yourself.
With this approach you will use a JavaScript variable valors for traversal in your JS function.
The similar approach can be taken if you want to update your array via AJAX.
The last thing worth noting is that this is merely a trick that is usually used to overcome a drawback in your design of JSF application. It could indicate both that you're using a wrong framework for the job mentioned and that you failed to find a proper instrument within JSF, but that's impossible to know given the information disclosed so far.
I'm pretty new to MVC and I'm just thinking ahead to my next project. I haven't been able to find any examples of how to do this, so I apologize if it seems like a question that may have already been answered somewhere else.
I'm going to want to create asynchronous cascading dropdown menus. So menu B will update as the values in menu A change, and menu C will update as either A or B update. What is the normal pattern for this?
Normally, as list events fire, I would use ajax to call a service that would process my input data and return json which I would use to update my lists. In this case, there is no service, only the controller feeding the view. We could create a service, but we prefer not to if at all possible. So I'm wondering if there is a technique in MVC4 that can feed me back what I need to update the view without re-rendering the page.
If someone could refer me to an example or at least explain what I might be looking for, that would be a great help. TIA
You can implement the Ajax callback URL as a controller action (in fact, that is how I typically do it).
There is no need for a separate service.
public class CallbackController : Controller
{
public ActionResult MenuOptions()
{
// return e.g. JSON
}
}
The Ajax URL would be
http://myserver.com/Callback/MenuOptions
There are a lot of answers around the web for this type of functionality. Here is one, and here is another similar example. What you should really do is read up on MVC actions / controllers and do some spiking / messing around.
Building the example starter app will help you get a grasp on the differences between classic ASP.NET and MVC.
I'm using breeze.js in a SPA and have problem with entities loaded from server. Namely, entity created from metadata (using metadataEntityType.createEntity()) and added to entity manager has all of the properties like server-side model, ready for binding with knockout, and that is cool.
The problem is when I use entityModel.EntityQuery.from("WorkOrders"), the successCallback that I pass to its .then promise gets a data object with results property which contains an array of vanilla js objects where all of the properties with value == null are missing (this is exactly how server sends that data through the wire, but I suppose that it is how is meant to be because breeze has all metadata on the client and does not need all properties to know that they exist).
I have my custom constructor which can make full-fledged knockout object like the one from createEntity(), but I'm thinking that there must be a better way to let breeze handle this for me automatically. I'm not sure if I should add these objects to entity manager as I suppose they should be already there, and I registered my custom constructor to store using entityManager.metadataStore.registerEntityTypeCtor, but that does not change what success callback gets, it is always plain JSON just like it was sent from server.
Update: Code of method which is called on the server to return json payload is
[HttpGet]
public IQueryable<WorkOrder> WorkOrders()
{
return (IQueryable<WorkOrder>)_contextProvider.Context.WorkOrders;
}
As #Jay pointed in its answer & comment, that may be the cause of behavior. This is the JSON payload returned:
[{"$id":"1","$type":"WorkOrders.Domain.Models.WorkOrder, WorkOrders.Domain","Approved":false,"DateModified":"2013-01-02T22:31:20.897","RequestForEstimate":false,"Id":5}]
This issue was caused by a model being in a different namespace than the DbContext/ObjectContext that hosted it. Previously this was documented as a known limitation.
As of v 0.83.2, breeze now allows model namespaces to be different from the DbContext/ObjectContext namespace.
Please confirm if this fixes the issue.
Thanks
I'm not quite sure I understand what you are asking. Is it that you would like properties with a null value on the server returned to the breeze client with a value of null instead of being undefined, or am I missing the issue?
If this is the issue, I agree that what you want would be useful and I will add it as a feature request.
Another possibility that you might want to look at is to use the 3rd parameter to the 'registerEntityTypeCtor' method that lets you pass in an initialization function. This function will be called once for each entity being constructed, 'after' it has already been materialized. This means that you can iterate over the properties or the object and set any that have a value of 'undefined' to 'null'
Does this make sense?
I would like to create a page for inserting a new car. I am using knockout.js and want to use knockout mapping. The problem is that for create, in order to get a structure for the mapping, I need to make an ajax call and return new and empty serialized object. Is there any to prevent this ajax call?
(I also don't want to write down the whole model structure by myself)
If you don't want to create a JavaScript version of your object and you don't want to do an ajax call to get it, it's not possible that Knockout magically knows the structure of your object.
What you could do, is use Fiddler to intercept the AJAX call. Fiddler will then show you the JSON representation of your object. You can copy paste this into your JavaScript so you have a 'cached' version of your model for first use. Pass this to Knockout and Knockout will create the object for you.
Of course the cached version will get out of sync with your server model (the same can happen with a plain JavaScript model). This is just something you have to deal with manually.
A way around this is to use a T4 template to do some code generation at compile time. Trough reflection you can generate a .js file with the up to date version of the model.