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

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?

Related

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

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

MVC JSON data reference

there is a call to my controller where something like this is performed:
someObject.Name = "Mike";
JsonResult result = Json(new { TheMan = someObject }, JsonRequestBehavior.AllowGet);
someObject.Name = "Paul";
return result;
The problem is that when the client receives the data, the name is "Paul" when I was expecting that the result JSON was created with "Mike".
In the docs it says "The result object that is prepared by this method is written to the response by the ASP.NET MVC framework when the object is executed."
Is there a workarround where I can manipulate the objects used on the JSON data without being worried about changing the response? (Clone the someObject or something)
Thanks.
You pretty much said it. When you create the Json object you are simply adding a reference to someObject so if you change the value it will be changed inside the Json object as well. The Json is not actually written to the response until the JsonResult is returned by the action. If you want to set the value to something else without affecting the original value you will need another copy of the object.

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.

Is there a way to pass a list of JSON objects from JS to C#?

Something I'm confusing.
The Javascript is going to produce the following JSON data.
{type:"book" , author: "Lian", Publisher: "ABC"}
{type:"Newspaper", author: "Noke"}
This is only an example, actually I've got more than this.
Since I have common fields between different JSON data, so I don't know is it possible to pass this to C# at one time.
What I want to do is pass this to c# then do some processing, what is the best way to do? I'm using ASP.NET MVC2.
Thanks for your answer or hints.
The combination of the 2 JSON statements above are, together, not valid JSON. That being said, you will not be able to use the JavaScriptSerializer class to deserialize that data into c# structure directly. Instead you will have to do some manual parsing first, to either break it down into valid JSON or just do full on manual parsing.
What I would actually recommend is sending over valid JSON instead. You can accomplish this by doing something like this:
{list: [
{type:"book" , author: "Lian", Publisher: "ABC"},
{type:"Newspaper", author: "Noke"} ]
Hard to say exactly, since only you know the details of your use case. You can send this data over using a traditional 'ajax' request. This is very easy to do with out any of the many JS libraries out there, but I would recommend just going with one anyway - they offer higher level constructs that are easier to use (and address cross-browser idiosyncrasies).
Since you are using ASP.NET MVC2, I would recommend jQuery. Microsoft is now backing jQuery as their JS library of choice and even make it default for new web projects.
Once you pass the above JSON to C#, you can deserialize it by doing something like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var result = serialzer.Deserialize<Dictionary<string, object>>(postedJSONData);
Your result will then have a structure that looks like this, in C#:
Dictionary<string, object> result =>
{ "list" => object },
object => List<object>,
List<object> => Dictionary<string, object>
{ "type" => "book", "author" => "Lian" } // etc
[
{type:"book" , author: "Lian", Publisher: "ABC"},
{type:"Newspaper", author: "Noke"}
]
Is still valid JSON (well actually keys need to be enclosed in " as well), so you can .push() into an array each time you create a JSON record.
var list = [];
// code doing other stuff
list.push({type:"book" , author: "Lian", Publisher: "ABC"});
// more code doing other stuff
list.push({type:"Newspaper", author: "Noke"})
Once your JSON list is constructed, you can send that list to the backend in one go.
You can also use the JavaScriptSerializer to deserialize your own custom type. Esentially you make a very simple type with all the properties of your json objects then call
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyType result = serialzer.Deserialize<MyType>(JsonData);
You can also deserialize an array
MyType[] result = serialzer.Deserialize<MyType[]>(JsonData);

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.

Categories

Resources