Passing a javascript function to ReactJS.NET Server side - c#

I have a pretty basic, but probably complicated question.
I am using ReactJS.net to render react components server side. I have a typeahead component which I use multiple times throughout my site. One of the properties it expects is a javascript filter function.
I don't want to have to create a seperate component for each instance of the typeahead, but would like to pass in a javascript function as a property so that I can reuse the component throughout the site.
For example, to render a component on the server I would do the following. The second parameter is the properties argment
#Html.React("Components.WorkSiteTypeahead", new { filterFn = model.SomeFunction })
Now as ReactJS.net expects native c# objects (string, array, list, etc), I don't see any straight forward way to pass in a Javascript function. Any ideas on how would I go about telling my MVC5 view to render my function not as a string? My first instinct is that there might be some sort of Javascript Raw type I am not aware of, but haven't been able to find it.

As I suspected, at least one way to go about this is to use Newtonsoft's JRAW Type.
#Html.React("Components.WorkSiteTypeahead", new { filterFn = JRaw("function(){//do stuff } "})

Related

Populating Html Helpers route arguments

Is there a way to populate anonymous type properties (route arguments) in Html Helpers like Html.ActionLink or Url.Action with data.
Example.
Create link like this:
Anchor Text
... and populate propertyValue with data extracted from current state of DOM (using Javascript).
I know there's a lot of ways that I can get that logic to work (ex. using form data and passing it to controller) but I'm just curious if a provided scenario is possible.
populate propertyValue with data extracted from current state of DOM (using Javascript)
No.
C# runs on the server, JavaScript runs on the client. You can't use JavaScript on the client to modify code which already ran on the server. You can use JavaScript to modify the markup which gets emitted to the client, and the first step in that would be to examine what that markup actually is. (In this case it looks like you'd be modifying a URL, which may involve some interesting string parsing in the JavaScript code.)
But no, JavaScript can't affect your calls to HTML Helpers.

Converting JavaScript variable to C#

I have a variable in JavaScript and I want to use it as an index reference in my C# code. How do I convert the JavaScript variable into something C# can use? So far this is what I have..
#{
var selectedStockLocation = #Html.Raw(Json.Decode(document.getElementById("cbLocation " + id).value));
var currentLocation = Model.StockLocationBinData[selectedStockLocation];
}
You will have to post the value back with either a full POST or an AJAX call.
You are mixing server and client code there.
You need to use (one of many) methods to post client data back to the controller.
Use jquery to write to a hidden variable in the form is one route, see this answer:
Passing a jQuery value to MVC 3 Razor view html helper
JavaScript runs well after the server-side code has rendered and completed; you cannot use it while rendering the view.. You can, however, store the value in a hidden field, put this hidden field in a form, and process it during a post operation. Or, send it to the server via an AJAX callback.

how to achieve calling a function dynamically, thats right the function to be called is decided from database values, using c#

the application is very large so giving a brief back ground and the problem
when the user logs in, a button is displayed having the text of the function he is allowed to call.
the function he is allowed is mapped in the database table
its made sure that the name of the actual function is same to the ones used in the db.
problem
the name is extracted, and stored as text field of button and also in a string variable.
now how am i supposed to call this function using the string variable which has the name stored in it!
like we type
name-of-function();
but here i dont know the name, the string at run time does so i cant write like
string()!!?
You will need to use reflection to do this. Here is a rough sketch of what you need to do:
// Get the Type on which your method resides:
Type t = typeof(SomeType);
// Get the method
MethodInfo m = t.GetMethod("methodNameFromDb");
// Invoke dynamically
m.Invoke(instance, null);
Depending on your actual needs you will have to modify this a little - lookup the used methods and types on MSDN: MethodInfo, Invoke
Well, no matter what you do, there is going to have to be some kind of mapping done between a database "function" and your "real" function. You can probably use Reflection using your Types and MethodInfo.
However, this sounds like a maintenance nightmare. It also sounds like you are reinventing user roles or the like. I would be very cautious about going down this path - I think it will be much more complex and problematic than you think.

Can I pass a linked list from a C# Web Service to a JavaScript function?

I've created a linked list class in my JavaScript code and then translated that code into C#.
Right now I have a JavaScript function that calls a Web Service in order to get an array of names, the JavaScript onComplete function then takes that array and makes it into a linked list.
Is there any way I can create the linked list in the Web Service and pass it back to be used by the JavaScript code or can linked lists not transfer properly?
Edit: Let me rephrase my question to something that makes a little more sense. If you have a custom made object created by a class say.... class User, and that class has a variable called user name. If you pass a User object: objUser, back from C# to JavaScript, how does the JavaScript know it can access objUser.userName? What about possible methods it can invoke on this user object?
I had a similar question when I was creating my ASP.NET MVC application. Basically the answer is that JavaScript does not have the same concept of Types as in C#.
Let's say that you've decided to use JSON to pass data between your client and server in your application. The choice of JSON, XML, YAML or other format is not important.
Server Side
On your server side, in your C# code, you can do something like this (assuming you are using a JSON library of some sort):
var myLinkedList = JsonConvert.DeserializeObject<LinkedList>(json);
Now you've got a myLinkedList variable of Type LinkedList. myLinkedList now behaves like all LinkedList instances.
Client Side
However on the client site, in your JavaScript code, you probably do something like this:
function LinkedList(){
//Constructor for your LinkedList
};
LinkedList.prototype = {
//Various functions to operate on your linked list
};
You need to write something like this to deserialize the data that returns from the server:
var linkedList = JSON.parse(jsonString);
Note that there is NO WAY to indicate that you want this deserialized data to go into the LinkedList "class" that you've defined earlier. JavaScript does not understand that LinkedList is a "class" that you've added functionality to using prototype.
What you get back is a JavaScript object.
One way to get around this is to do something like this:
var linkedList = new LinkedList();
var deserializedObject = JSON.parse(jsonString);
linkedList.Items = deserializedObject.Items;
Basically, you'd have to copy over all the state from your deserialized object into your linkedList variable.

ASP.NET MVC Data Feedback through User Controls

In our new product we have a few data entry fields that require you to search for the correct value to place in this field.
When you enter this data entry field I would like to provide a search option via something on the view (perhaps an Ajax implementation) and have it allow searching of the database for the value, but when the result returns I want to keep the existing values in place for other fields not affected by the search.
But I have no idea how to do this with MVC. Does anyone have any suggestions on how this should be done?
Write your data entry page in the
usual way for an ASP.NET MVC view.
Get it working without the Ajax
(e.g., submit works correctly when
you just type in the values, without
auto complete).
Write the prototype for a JavaScript method you'll called when the user performs a certain action (e.g. presses a key inside of a certain control). But this inside a script tag in your aspx page. Unfortunately, stack overflow seems to "sanitize" script tags in my example, so I can't demonstrate that part. But you're JavaScript prototype will look something like this:
function startAutoComplete() {
}
Now hook up the event handlers on the user interface control. You need to call the function you've just prototyped an appropriate event handlers for your application. From your description, it sounds like you might want to use onkeydown, but there are lots of events to choose from. You probably need to handle more than one event, as appropriate for your application.
So far, everything that we've done has been standard aspx and JavaScript. In this step, we'll do the only part of the whole process which is really different for ASP.NET MVC. You need to add an action to your controller which will be called (indirectly) by the JavaScript prototype you've just written. The action should accept appropriate input (e.g., a string representing the text from control, or something like that, as appropriate for your application) and return its results in JSON format. I'm going to show a really simple example here; feel free to substitute more complex code in your real application.
public ActionResult GetSuggestions(string searchText)
{
return Json(new {SearchText = searchText});
}
This example just returns a JavaScript object containing one property, which contains the value passed to the function. Like you said, you can write something more useful for your application.
Now you need to call this function in JavaScript. The URI will look something like:
http://localhost/mycontroller/GetSuggestions?searchText=Foo
It is possible to make Ajax calls without a JavaScript library, but much easier if you use jQuery or some other library which handles cross-browser compatibility issues for you. Since I happen to like jQuery, I'll demonstrate that. Let's update the startAutoComplete method we prototyped earlier:
function startAutoComplete() {
var searchText = $("#myeditorid").text();
$.getJSON("/mycontroller/GetSuggestions?searchText=" + searchText,
null,
autoCompleteResponse);
}
The first line uses jQuery to get the text in the control with the ID myeditorid. We'll pass this to the ASP.NET MVC action as the searchText argument, by appending it as a query string parameter.
The next line, which starts with $.getJSON calls a jQuery function which makes an Ajax call to the URI you specify. We pass an argument, autoCompleteResponse, which is the name of a JavaScript method to be called if the response from the Ajax call is successful. Now we have to write autoCompleteResponse.
function autoCompleteResponse(data) {
if (data.SearchText)
{
$("#myeditorid").text(data.SearchText);
}
}
This says, "If the data returned has a SearchText property, set the text of the control to that value." Again, do whatever is appropriate for your application with the data returned.

Categories

Resources