Best way to transfer data from view to javascript - c#

I'm working in an Asp.Net MVC 3 project where in one of my javascript file, a message is displayed to the user. This message in currently in one language but I want this message to be in multiples languages. I don't want to store theses languages directly in the javascript file but instead in a database. I want to know if it possible to transfer data (string) from the view to the javascript file.
One solution that I've found is to set data from my view in hidden fields and then extract it from my javascript file. The problem with this solution is that I must put a lot of hidden fields and this is very hard to maintain.
Is there any other solution to this problem?

You can try JavaScriptModel ( http://jsm.codeplex.com ).
With this library you can add variables by calling the following function in your controller action:
this.AddJavaScriptVariable("VariableNameInJavaScript", SomeValue);
You can pass primitive types or complex types.
Furthermore you could execute javascript functions with the following code in your controller action:
this.AddJavaScriptFunction("FunctionInJavaScript", SomeParameter, AnotherParameter);

Yes, your on the right path. All you need to do is hydrate your model appropriately and use Razor syntax to pass the value from the server to the client "along the following lines":
<script src="#Url.Content("~/scripts/yourapi.js")"></script>
<script>
yourapi.foo('#Model.SomeValue');
</script>

Related

Call controller function in cshtml where the string is from a database value

I am trying to have a column in my database where the string stored is:
'"Test count:" + #mycontroller.count()'
And then in my cshtml file do
<li>#Html.Raw(#MenuItem.ItemText)</li>
However, all I am getting displayed is the string in the database and not it the actual result from the controller count() function. How do I get that string to render/execute?
You cannot call a function in a Controller from a view since you don't have an instance of such controller on you view. There are 2 ways of doing what you want:
Having an action on your Controller that given the string you want to use returns the data you require and make an AJAX call to get it
Calculate the data you want before you render the View and pass it in along your model, either using ViewBag|ViewData or as part of your View Model
If understand your intention correctly, you are trying to store C# code in the database and then execute it in your view. That will not (by default) work, since C# is statically compiled language, which means that each change to your code needs to be first compiled to binary code before the code can be executed.
The same applies to MVC razor syntax views (cshtml files) - when a cshtml file is first requested, it is compiled to binary code and then executed.
If you are certain about what you want to do however, there perhaps may be a way, as described in this SO post. But I would first recommend you to describe exactly what it is you are trying to achieve that you ended up with this question.

How to serialize an object in MVC 5 Razor view

I have tried to follow this post in order to create a 3 page form wizard that passes data to each page.
He uses the HTML helper serialize, to serialize an object in the view.
#Html.Serialize("wizard", Model)
However this HTML helper isn't available in MVC 5 it seems.
I found another related post to this here where he suggests using the following to serialize the object.
#Html.Hidden("otherComplexData", new Microsoft.Web.Mvc.MvcSerializer().Serialize(complexObject))
But I then get the following error
There is no argument given that corresponds to the required formal parameter 'mode' of 'MvcSerializer.Serialize(object, SerializationMode)'
It seems to want a SerializationMode, however the documented one doesn't. https://msdn.microsoft.com/en-us/library/microsoft.web.mvc.mvcserializer.serialize(v=vs.118).aspx
What direction can I go in now?
Thanks.
Here's the Serialization option you need:
https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/MvcFutures/Mvc/SerializationMode.cs
Options are Signed or EncryptedAndSigned.
You can try that and see if it will work.
There's multiple ways to encode data that will work for you. You could put the values in a hidden input using Json.Encode for the view, and Json.Decode on the server side.

pass value from apicontroller to view in asp.net mvc4

I have list of data in my api controller.
I want to pass this data to view using something similar to viewbag.
I know we cant use viewbag in apicontrller , So Is there any alternative for it.
Normally ApiControllers do not return views. They return models, or HttpResponseMessage for that matter. So you could simply have a view model that will contain the required property and then have your API action return this view model.
You are not supposed to tho that, the API controllers return only data (XML, Json, etc). So you should have two controllers:
System.Web.Http.ApiControlle Use this to return collections of data for example:
public List<Company> Get()
{
return this._companyService.GetCompanies();
}
Returns a list of companies in Json or XML not a view.
System.Web.Mvc.Controller use this one for returning HTML without data for example an HTML table without rows or client-side templates.
How to link the two? The idea is to render in the client-side with JavaScript, there is a good few reasons to do it this way, the main ones are that you have data and presentation in two completely separated feeds so you will be able to re-use your data feed (in mobile apps for example).
To render in the client-side is good idea to use some JavaScript rendering engine, take a look to http://handlebarsjs.com/.
Use Jquery.getJSON() to get your JSON and get your handlebars template from your DOM or via Ajax, select a DOM alement to insert the generated HTML. Once you have the JSON, template and container use the function below:
function RenderJson (json,template,container) {
var compiledTemplate = Handlebars.compile(template);
var html = compiledTemplate(json);
$(container).html(html); //set new content
}
I know it can seem like a more complicated process but it you try it you will see the advantages, you will be able for example to test your data feed and your data presentation separately.
Hope it helps :)

Can I manage C# variable into .js?

I have my script.js into the folder script.
I'd like to manage, into that script, some C# variable, from a Web Form (e.g. <%= myString = 3 %>).
I think this is not possible, but maybe can I do it in some way? Thank you
Javascript is client side executed code, and C# is server side executed code. So you can't strictly make a "variable" visible, as they're two completely different code platforms/runtimes, running on two different computers. However you can still marshal the data between them in a few different ways.
Write a web service and call it via AJAX
Populate a control or your URL for your page with your data, and query it via the Javascript DOM API (or via some wrapper library like jQuery)
An example of the 2nd (since you asked):
<!-- Somewhere in your page -->
<span style="visibility:hidden" id="myData"><%= myString %></span>
// In Javascript, using jQuery:
var myData = $('#myData').text();
If the variable is directly related to a particular element on the page then you should definitely consider using the HTML5 data-* attributes to store the value. Imagine the variable pertains to the an anchor element, you could output like so:
Blah
You can then access the variables with jQuery like so $("#myLink").data("myVar") (note the camel case). jQuery will attempt to convert value to the correct type. If you want the raw value then just use the attr jQuery method like this $("#myLink").attr("data-my-var") (note the attribute name has not changed).
Alternatively you could do the following in your server-side code to output to your page:
<script type="text/javascript">
var myVar = <%= someVariableToOutput %>;
</script>
As long as this code is output above your dependent script it will be accessible as with any other JS variable.
Finally, you could execute an AJAX request when the page is loading and get the variable that way (though this may not be applicable if the data is only available during the main request)
Hope that helps

Passing .CS arraylist to JQuery

I am trying to create an autocomplete text box based on an ArrayList from my main page's cs.
I am fairly new to JQuery and I am wondering what the best way to call the ArrayList from that page would be.
I feel like I have search all terms possible but all I can find are AutoComplete examples that either create the Array in a variable before it executes the script or it makes a vague reference to calling a URL.
Thanks for any information on this.
This is what I have so far in my newby experience.
<script type="text/javascript">
$(document).ready(function(){
$("#example").autocomplete("Requests.aspx.cs");
});
</script>
A few things....
You don't call Request.aspx.cs (that is a code file that gets compiled). The client served page is Request.aspx, and that's what you need to call.
Since you're using the jQuery UI Autocomplete, the Request.aspx will need to respond with JSON data in the correct format (I believe it is a 3 field object with id, name and value).
Request.aspx will need to be setup to take in a parameter (I believe it is called term), do logic to lookup, and return the results of that lookup serialized as JSON. There are C# classes to help with JSON serialization.
You've got quite a few things you need to go figure out in order to achieve this. Hopefully the above will help get you started.
You can create a $.ajax request for the page Request.aspx, whose code behind should return your data. Then use the jQuery autocomplete.
Edit:
If you want to take the approach that Matthew has suggested, I would suggest checking out this page ASP.NET AJAX from ScottGu, as it describes a way to make server-side service calls directly from your javascript and should eliminate any mess JSON handling on your end.
May be you could expose some kind of restful service for this purposes.

Categories