Access ViewData Using JQuery - c#

I am developing a mvc application.I wrote a jquery for different operations and saved in to a js file named my.js. And i included that js file into my page.
<script src="../../Scripts/my.js" type="text/javascript"></script>
How can i access ViewData from that js file. I tried many methods.But didnt worked yet.
The code i used to access ViewData from js file is shown below.
var CalanderPreference = "<%= ViewData["CalanderPreference"] %>";
But it returning an error like 'Expected ; '
Any ideas?

ViewData is not accessible on client, because it exists only on view rendering.
You could serialize your view data to json on server side, write it to hidden field, and them parse it to javascript object on client side.

You can create your javascript object on the view like in this example.
Put this into your view and not in a seperate file:
<script type="text/javascript">
$(function() {
var saleYear = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Year %>");
var saleMonth = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Month %>") - 1;
var saleDay = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Day %>");
var saleHour = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Hour %>");
var saleMinute = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Minute %>");
var saleSecond = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Second %>");
var endSaleDate = new Date(saleYear, saleMonth, saleDay, saleHour, saleMinute, saleSecond);
$("#countDownSale24").countdown({ until: endSaleDate, compact: true, format: "HMS" });
});
</script>

Related

How to pass generic list of values to external js file from controller/view in ASP.NET MVC

The file name is called clik.js here I have to access some values from controller/view
Using view I have tried this code:
<head>
#if (ViewBag.status != null)
{
<script type="text/javascript">
var tagAccess='#ViewBag.status[0]';
</script>
<script src="~/JavaScript/click.js"></script>
}
</head>
Using this code, I could get single value in js file. But I have to get all values
//var tagAccess='#ViewBag.status';
If I write the code like this, I didn't get any output
You can serialize the Item using this:
<script>
var tagAccess = #Html.Raw(Json.Serialize(#ViewBag.status[0]));
</script>

How to pass custom JavaScript through ASP.NET Core

I am implementing a simple JQuery autocomplete with few entries so I don't need to use a web method. The code is like this:
$( function() {
var availableTags = [
"ActionScript",
"AppleScript"
];
$( "#tags" ).autocomplete({
source: availableTags
});
} );
The entries availableTags are unique to the user so they need to come from the server. How should I get the entries from the server side to the JavaScript in ASP.NET Core?
This assumes you have some service IUserTagService like this, registered through dependency injection:
public interface IUserTagService
{
IList<string> GetUserTags();
}
Since you don’t want (or need) an AJAX call here to load the tags after the page has been rendered, we’re just going to render the tags directly into the output. For that, we basically convert the returned list from the GetUserTags method into JSON and put this into a script tag. So the end result will look mostly like your static example.
So in the .cshtml view, we first inject our service. We can use the #inject directive at the beginning of the file for this:
#inject IUserTagService userTagService;
Then, we simply open a script tag and write the output into a variable:
<script>
$(function() {
var availableTags = #Json.Serialize(userTagService.GetUserTags());
$("#tags").autocomplete({
source: availableTags
});
});
</script>
This uses the Json.Serialize which is a utility function that is available in views to serialize the list into JSON.
You can make an ajax call to your server action method which returns the list as JSON array.
$(function () {
$.getJSON("#Url.Action("GetItems")", function (availableTags) {
$( "#tags" ).autocomplete({
source: availableTags
});
});
})
Assuming your GetItems action method returns the list of items as json array
public JsonResult GetItems()
{
var list = new List<string>() {"ActionScript","AppleScript"};
return new JsonResult(list);
}
Another option is to load the data (list of strings to your main views GET action method and in the razor view, convert that to a JS Array
So in your GET action,
var list = new List<string>() {"ActionScript","AppleScript"};
ViewBag.Items = list;
return View();
and in the razor view,
#section Scripts
{
<script>
$(function() {
var availableTags = #Html.Raw(Newtonsoft.Json.JsonConvert
.SerializeObject(ViewBag.Items));
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
}
Dependency injection is possible in asp.net core views now. poke's answer above uses that. You may consider doing that instead of the ViewBag solution above.

Writing Javascript with Razor and Resharper

I am trying to write the following javascript in Razor (MVC4).
(The Script tags are there)
var isPaid = true;
in the view I use the Model to get the value:
var isPaid = #Model.Paid;
<text>
var proceed = #Model.Paid;
</text>
var proceed = #Html.Raw(Model.Paid + ";")
Most of the time Resharper complains
You could try it this way:
<script type="text/javascript">
var isPaid = false; // This is JavaScript.
// The if statement is C#, hence the #.
#if (Model.Paid)
{
#:isPaid = true; // Set the JS variable to true.
}
// Below is JavaScript code again.
alert(isPaid);
</script>
Text after the #: nugget will be interpreted as as JavaScript. It is a bit of a hassle for booleans, a string property for example is a lot easier:
<script type="text/javascript">
var userName = '#Model.UserName';
</script>
You can't combine JavaScript inside HTML code and you need to put quotes & angle-brackets around the value so that it is considered as a string.
The problem seems to be this and more..:
var isPaid = #Model.Paid;
<text>
var proceed = #Model.Paid;
</text>
A proposed solution would be:
Normal JavaScript code should resides within a script tag, for example:
<script type="text/javascript">
var isPaid = '<%: #Model.Paid %>';
</script>

Assigning C# variable value using javascript variable in code behind

I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
alert(pic);
});
});
});
</script>
There is no way to assign a C# variable by javascript.
You have to send that value from the client (where you JavaScript is running) to the Server, and assign it.
This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.
create a hidden filed and then set the value from javascript
<asp:hiddenfield id="hf_MyValue"
value="whatever"
runat="server"/>
How To Set value in javascript
//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";
Create a hidden variable like this,
<input type="hidden" id="hdnVariable" runat="server" />
Now try this code
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
//assign value to server side hidden variable
$("#<%=hdnVariable.ClientID%>").val(pic);
});
});
});
</script>
Now you can access this hidden field from C# code like this
string pic=hdnVariable.Value;

How do I access ViewBag from JS

My attempted methods.
Looking at the JS via browser, the #ViewBag.CC is just blank... (missing)
var c = "#" + "#ViewBag.CC";
var d = $("#" + "#ViewBag.CC").value;
var e = $("#" + "#ViewBag.CC").val();
var c = "#ViewBag.CC";
var d = $("#ViewBag.CC").value;
var e = $("#ViewBag.CC").val();
if you are using razor engine template then do the following
in your view write :
<script> var myJsVariable = '#ViewBag.MyVariable' </script>
UPDATE:
A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```
<head>
<script>
var AppConfig = #Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
And you can use it in your JavaScript code as follow:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
try: var cc = #Html.Raw(Json.Encode(ViewBag.CC)
<script type="text/javascript">
$(document).ready(function() {
showWarning('#ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
ViewBag is server side code.
Javascript is client side code.
You can't really connect them.
You can do something like this:
var x = $('#' + '#(ViewBag.CC)').val();
But it will get parsed on the server, so you didn't really connect them.
You can achieve the solution, by doing this:
JavaScript:
var myValue = document.getElementById("#(ViewBag.CC)").value;
or if you want to use jQuery, then:
jQuery
var myValue = $('#' + '#(ViewBag.CC)').val();
None of the existing solutions worked for me. Here's another solution I found that did work:
Controller:
TempData["SuccessMessage"] = "your message here";
View:
let msg = '#TempData["SuccessMessage"]';
Try this:
Anywhere in HTML: <input hidden value=#ViewBag.CC id="CC_id" />
In JS: var CC= document.getElementById("CC_id").value.toString();

Categories