Using C# object in razor view page - javascript

I have this rows of c# code in View razor page:
#{
List<UserContact> userContacts = ViewBag.contacts;
String contacts = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
}
I want to use the content of contacts variable in JavaScript function since the contacts is a C# object I cant use this variable in JavaScript function.
Is there any way to use contacts variable in Javascript function?
Maybe since the type is string it can be converted to JavaScript variable?

You can use # directives like you would normally do. You can print it using Html.Raw:
var x = /* this is javascript */
#{
...
#Html.Raw(contacts)
}
Or just call #Html.Partial directly:
var x = /* this is javascript */
#{
...
#Html.Partial(...)
}
Or declare it here:
#{
...
string contacts = #Html.Partial(...)
}
And use it later:
#contacts

Yes there is, you only need to render it inside a script block. Try this:
<script>
var contacts = '#contacts';
alert(contacts);
</script>

Related

How to transfer a serialized JSON string from C# code behind to use in Javascript

The ultimate goal here is to populate fields of a Bootstrap modal from an object in the C# code behind that has all the data I need. I serialized the object from the code behind, like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
sJSON = serializer.Serialize(aerationsystem.AerationSystem);
Now I want to reference that JSON in my Javascript function, like this:
</form>
<script type="text/javascript">
function fillModal() {
var diameterValue = document.getElementById('diameter');
var aeration = <%# sJSON %>;
diameterValue.innerText = aeration.dBinDiameter;
}
</script>
</asp:Content>
(I included that closing form tag and the closing asp:Content tag so you all could see where it was that I put this Javascript: at the very end of the file.)
However, when I call that Javascript function, this is what I see in the browser's debugger:
<script type="text/javascript">
function fillModal() {
var diameterValue = document.getElementById('diameter');
var aeration = ;
diameterValue.innerText = aeration.dBinDiameter;
}
</script>
I got the idea from here: Any way to pass an object from c# code behind to javascript?
But, the means of accessing that JSON variable does not work for me. I've tried moving my script, but when I do that, I get an error that says "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).". And I've tried other delimiters, like <%= %>, but I get the same errors depending on script placement. What am I doing wrong? How can I get that JSON string to show up in my Javascript function?
<%# %> syntax is for binding data from data source.
The easiest way is to use a Literal Server Control. It seems a bit weird inside script tag, but it does the job.
<script type="text/javascript">
function fillModal() {
var diameterValue = document.getElementById('diameter');
var aeration = <asp:Literal id="JsonLiteral" runat="server"/>;
diameterValue.innerText = aeration.dBinDiameter;
}
</script>
Code Behind
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonLiteral.Text = serializer.Serialize(aerationsystem.AerationSystem);
<%# %> is a binding block so you need call the Page.DataBind() method, whether in the Page_Load or the Page_PreRender event.
You also need to curate the string so the JSON text doesn't break your javascript:
var aeration = '<%# sJSON.Replace("'", "\'").Replace("\n", " ") %>';
thank you so much for taking the time to answer my question! I ended up solving the problem, with some inspiration from you all. Instead of using a Literal control, I ended up using a <asp:HiddenField> control on the page to store the value. Then, I pulled that its value into the Javascript variable.
The hidden field: <asp:HiddenField ID="JsonLiteral" runat="server" />
The code in the event that assigned the value:
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonLiteral.Value = serializer.Serialize(aerationsystem.AerationSystem);
And the JavaScript that finished the job:
function fillModal()
{
$(document).ready(function () {
var diameter = document.getElementById('diameter');
var control = document.getElementById('<%= JsonLiteral.ClientID%>');
var aeration = JSON.parse(control.value);
diameter.innerText = aeration.dBinDiameter;
});
}
(There's gonna be a lot more to it than just that one property, of course.)
Again, thank you all for you help, because I could not have done it without you!

Passing Dictionary from controller to Javascript

I have a view model like this:
public class weightdata
{
...some properties
public string weights;
}
Then, I have in the controller:
weightdata details = new weightdata();
Dictionary<string,float> dict = new Dictionary<string,float>();
//do something to fill the dictionary with values
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
details.weights = ser.Serialize(dict);
return View(details);
Then in the view:
<script type="text/javascript">
var dict = #{Html.Raw(new JavaScriptSerializer().Deserialize<Dictionary<string,float>>(Model.Weights));}
</script>
But the rendering of the page is:
var dict = (it's blank)
How can I get this dictionary of values into where it can be used by javascript?
Your property is already serialized, meaning it's already JSON. You don't want to deserialize it on the view, just write it out directly:
var dict = #Html.Raw(Model.Weights);
The other alternative is to make your property a Dictionary<string, float> instead of a string, then you would serialize it on the view:
var dict = #Html.Raw(new JavaScriptSerializer().Serialize(Model.Weights));
Something I just recently read about which may make your view a bit cleaner - you can actually dump the JSON into its own script tag with type="application/json", and reference it in javascript. This may make your editor a little happier, since it's easier to separate the javascript from the C# code.
Something like:
<!-- assuming your Weights property is the serialized JSON string -->
<script id="some-json" type="application/json">
#Model.Weights
</script>
<script type="text/javascript">
var dict = JSON.parse(document.getElementById("some-json").innerHTML);
</script>
Just make sure you're targeting IE8+ or a real browser - if you need IE7 support, you'll need something like json2.js.

How to get spring mvc controller model key value inside javascript?

I am using a spring mvc controller. Inside controller i am putting some value lets say string inside model. Now i would like to retrive that value or lets just say print that value inside a javascript. How do i do it?
Here is my controller class. I am adding "movie" as key. Now i want to display that name of the movie inside java script (Not inside JSP. However Inside JavaScript)
#Controller
#RequestMapping("/movie")
public class MovieController {
#RequestMapping(value="/{name}", method = RequestMethod.GET)
public String getMovie(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return "list";
}
}
here is my JSP
<html>
<head>
//I want to print movie name inside java script not inside jSP body tag.
<script type="text/javascript">
var movie_name = ${movie};
alert("movies name"+ movie_name);
</script>
</head>
<body>
<h3>Movie Name : ${movie}</h3>//When i print here its working fine.
</body>
</html>
Use this:
var movie_name = "${movie}";
instead of:
var movie_name = ${movie};
When using ${movie}, the value gets placed on the page without quotes. Since I'm guessing it's a string, Javascript requires strings be surrounded by quotes.
If you checked your browser's console, you probably would've seen an error like Unexpected identifier or ___ is not defined.
Try this...
If you had added the object into the model as:
model.addAttribute("someObject", new Login("uname","pass"))
Then you get the properties of the model object as
var user_name = ${someObject.uname}; // This is assuming that the Login class has getter as getUname();
var user_pass = ${someObject.pass};
<html>
jsp code ...
<script>
some js code ..
..
var formProperty = <c:out value="${fromBean.property}" />
</script>
..
</html>
This worked for me where formBean is the name of form backing object and property is filed of the form class

How to access a variable in a function from inside a jsp tag

I have the following function:
<script>
function assign()
{
var val = "";
val = document.form1.text1.value;
alert(val);
}
I want to access the variable val's value inside jsp tag so that i can pass it to the googlePlus method as a String. I tried making var val as a global variable, but it doesnt work. How can I access the variable val inside the following code?
<%
String output = "";
if ( Boolean.valueOf(request.getParameter("submitted")) == true ) {
Scraping h = new Scraping();
output = h.googlePlus();
}
%>
You can assign the value of the variable using a assignment operator to some hidden JSP field and then use it in the JS using document.getElementById(). the code would be somewhat like:
<input type="hidden" value="<%=output%>">
Or alternatively if your js is residing inside the JSP only
var s = "<%=output%>"; should work!
Cheers!
You can't access javascript variables via JSP Java Code.
Your JSP & Java codes are compiled at server side.
And your javascript runs in a browser.
So send the 'val' variable to your servlet by form submit, ajax or whatever.

Accessing global variables in JavaScript functions

I am using C# asp.net mvc3.
In one of my views, say I declare a variable like this:
#{
ViewBag.Title = "title"
string mystr;
}
I need to set the value of the variable mystr in a function of the script. How do I access this variable from the script?
Suppose I have a function like
<Script type="text/javascript">
function(){
var st = "This string is for the global variable"
mystr = st;
}
</script>
mystr will later be used in the html code like this:
<h2>#mystr</h2> .
Is there a similar way of accessing a variable from a function?
mystr in your example is server side variable that lives during cshtml view parsing. So you can't affect it with JS code on the client side. You can try something like this:
<script type="text/javascript">
window.mystr = #(mystr); // Set value while server side processing.
function(){
var st = "This string is for the global variable"
window.mystr = st; // Get/Set value
}
</script>
And use global variable mystr on client side wherever you need.
If you need then set header's text via JS you can do it for example with jQuery:
<h2 id="header"></h2>
JS:
$('#header').text(window.mystr);

Categories