How do I pass data from c# to jquery/javascript? - c#

I have a function that I'd like to run when the page loads, so either in document.ready or pageLoad.
Using jquery, I'll trigger the function using its class name
In document.ready
var span = $('.linkify');
span.html(textToLinks(span.html()));
Elsewhere
function textToLinks(text) {
var exp = /(my text)/ig;
return text.replace(exp, "<a class='link' href='http://www.bbc.co.uk' target='_blank' >$1</a>");
}
Now this works with the simple test data, but I need to now work out how to expand the functionality.
I have a list of terms in my c# app, along with the relevant url. I'm thinking of passing this data as a string, and splitting in, however my javascript knowledge has a lot of holes.
So I suppose I have 3 questions:
How do I get my string into the function when the page is loaded?
Is a string the right type or can I pass some other dictionary object?
How do I iterate through each of the terms passed efficiently?
Thanks in advance.

What you can do is, use JQuery Ajax call to retrieve server side data.
But that would require you to set up service that would be exposed. You could do it in a shortcut way with out setting up the service.
But that would require messy logic.(its a short cut :))
You could create a property in your page which exposes the JSON Data as string. You could read the JSON data in your javascript by following
var data =<% GetData() %>
You can define a ToJson on object to convert the object in to JSON String
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
return serializer.Serialize(obj);
}
public string GetData()
{
return (new {SomeData}).ToJson();
}
Note SomeData is a class containing your data(i.e array of urls) or what ever representation you choose.
Then loop over data to build the dynamic html

#Anand is correct saying that you can use jQuery Ajax to retrieve server-side data.
However, depending on exactly what it is you want to do, you might be able to do it another way.
You can use the .net JavascriptSerializer class to serialize your data to JSON format. JSON is a very good tool to become familiar with if you aren't already familiar with it.
JavascriptSerializer will put your JSON in a string, which you can then put inside a hidden input and read with your Javascript code. This has the advantage that there is no need for a second HTTP request, as would be the case with jQuery Ajax.

If you've got your data in advance when the page is loaded, you can write the JSON directly to the page, then use that javascript object to do whatever you need.
I don't know if you're using MVC or WebForms, but the idea is basically the same:
For example (using JSON.NET to serialize):
<script id="some-data" type="application/json">
<%= JsonConvert.SerializeObject(someDotNetObject) %>
</script>
<script type="text/javascript">
var _someJsObject = JSON.parse(document.getElementById("some-data").innerHTML);
</script>
Now _someJsObject is a javascript object representing the data you started with, and you can do whatever you want with it, like looping through an array, etc.
Side note - if you're targeting IE7, you'll need to use something like json2.js to get the JSON parsing.

Another possible way of doing this is to write the javascript function at page load in your C# code. This will then be added to the page when it is rendered and can be executed by the jQuery on document.ready(); or any other function / event.
Example code :
string FunctionStr = "<script type=\"text\javascript\">function textToLinks(text) {" +
"var exp = /(my text)/ig;" +
"return text.replace(exp, \"<a class='link' href='http://www.bbc.co.uk' target='_blank' >$1</a>\");" +
"}</script>";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Some JS Function", FunctionStr);
The answers from Anand and Daniel may better suit your desired approach but this is a 3rd option if you desire one.

You can do this way :
Declare public member into your C# class on code behind
public string mystring;
Initiate it in Init or Load Event
And write that on your js function
var exp = '<%=mystring %>';
It should work for string. For Dictionnary, you may try to do Ajax

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.

Using a List<> as a model - asp.net mvc

So I am returning a view with a List as a model as such:
List<Indications.Analysis.PrepaymentResult> resultsList = Indications.Analysis.PrepaymentResult.GetPrepaymentResult(indication.Model.Trx, indication.Model.ShockBpsDropList.Value, indication.Model.ShockIncrements.Value);
return View(#"~\Views\Indications\TermSheetViews\Swap\PrePayment.aspx", resultsList);
This compiles but, can I do this?
I need to work with this list in javascript, I have code on another page that gets the list in Json from AJAX but in this case I don't have the ability to do that. How would I then work with the list that I am passing in through javascript, with the following method:
CreateShockTable(data.prepaymentList, "TotalValueString", "#valueTable", "Prepayment Value");
That prepaymentList is this list.
You could serialize the model into a JSON object using JavaScriptSerializer:
<script type="text/javascript">
var prepaymentList = <%= new JavaScriptSerializer().Serialize(Model) %>;
// TODO: use the list here, for example pass it to some function:
CreateShockTable(
prepaymentList,
"TotalValueString",
"#valueTable",
"Prepayment Value"
);
</script>
Yes, you can.
var myList = ViewData["whatever"] as List<Indications.Analysis.PrepaymentResult>;
It is translated into JSON Array during serialization, so you can easily loop through it.
I don't clearly understand what do you mean by "passing in through javascript". Is it a result of the action called through Ajax?

Working with JSON on the Server-Side in ASP.NET and C#

I have an ASP.NET web form that is using JQuery on the client-side. I have a user interface that is building a collection of objects and storing them in JSON. With my client-side implementation complete, I need to now work with that information when the user clicks a button. When this button is clicked, I need to loop through that JSON collection and validate the entries. My problem is, I'm not sure how to do it.
// Client-Side Code
var myCollection = {
"data": [
]
};
// Server-Side Code
protected void myButton_Click(object sender, EventArgs e)
{
// Parse JSON
}
Each item in the collection is stored in the "data" property. How do I loop through the JSON collection on the server-side? I thought about putting the JSON data in a Hidden HTML Element, but this didn't sound good and I could think of a good way to do it.
Thank you
How you send it to the server is up to you - a hidden field, an AJAX call, whatever you prefer. Once you've got the string on the server, you'll need 2 things:
A C# server-side representation
of that object
A converter to go
from JSON to that C# representation.
Let's adjust your example a bit, because "myCollection" in your example is an object, not a collection. So we'll call it myObject. Secondly, we'll assume that "data" is an array of strings. It could be anything, but we'll keep it simple.
var myObject = {
data: ["string1","string2"]
};
We'll also assume you're using the DataContractJsonSerializer, so you can easily map the two different case-styles...JavaScript is typically camelCase, and C# is typically ProperCase. So, in C#, this would be:
[DataContract(Name="myObjectType")]
public class MyObjectType{
[DataMember(Name="data")]
public string[] Data { get; set; }
}
Now you have two representations of the same structure, one in c#, one in JavaScript. To convert from one to the other, we can use the built-in DataContractJsonSerializer, like this:
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
...resulting in a final call of:
MyObjectType myObject = Deserialize<MyObjectType>(incomingString);
JSON in the Hidden Field is a valid way to do it, as the data would then be posted to the server. You could then use the System.Web.Script.Serialization.JavaScriptSerializer component to deserialize the data (to a dictionary) and access the data that way. Not 100% sure hhow array data comes out of that process. THere are also other tools like JSON.NET too to parse JSON.
Another way is via a web service call, but that doesn't go through the page lifecycle.
HTH.

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