How to pass parameters to referenced javascript file from razor view - javascript

If i have such javascript in my razor veiw:
#{
Grid grid = #Model.GetGridFromModel();
Bool isSomething = #Model.GetSomething();
Bool isSomethingMore = #Model.GetSomehtingMore();
Bool isSomethingElse = #Model.GetSomethingElse()
int caseCount = 0;
}
$(document).ready(function () {
$("#tabs").tabs({
show: function (event, ui) {
switch (ui.index) {
#if (isSomething){
<text>
case #caseCount:
change('#grid.Avalue');
break;
</text>
caseCount++;
}
#if(isSomethingElse){
<text>
case #caseCount:
change('#grid.Bvalue');
break;
</text>
caseCount++;
}
#if (isSomethingElseMore){
<text>
case #caseCount:
change('#grid.Cvalue');
break;
</text>
}
}
}
});
funciton change(id)
{
//doing somehting;
}
So i want to put that javascript in separate file and reference that file to my view, and the problem is how may i pass values from razor to javascript when javascript in separate file?

Javascript are files without being parsed by the compiler, so, you have no chance...
What you can do however is to use a dynamic javascript, for example:
<script src="/CustomScripts/scripts.js"><script>
Have a route that says:
routes.MapRoute(
"CustomScripts", "CustomScripts/{id}",
new { controller = "Scripts", action = "GetFile" }
);
Create your controler and use a simple return View(); like
public ActionResult GetFile(string id)
{
// use id as you please
// pass any Model you want
return View();
}
In that view, just put your javascript with Razor syntax.
Or you can use variables and load them up make the use of RenderSection()
in your _Layout.cshtml file add a section in your <head> before any other javascript
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#RenderSection("script_variables", false)
<script src="#Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
</head>
and in any View that you want to add such variables, just do:
#Section script_variables {
<script type="text/javascript">
var variableA = '#MyVarA',
variableB = '#MyVarB',
variableC = '#MyVarC';
</script>
}
And all other files that you load the script will have such code...

You might declare some js-variables on your page and then use those variables from the .js-file
You might call a function inside your .js-file and send your data as arguments
(Please consider creating one object and fill with your data instead of creating multiple variables.)

Related

Update Values and show in .cshtml at every specific time interval

I am using visual studio serenity template for my aspnet MVC application. For example what I want to do is to generate random values at every 1 second in controller and pass it to cshtml page <div>.
Please help me how can I refresh my page at every 1 second.
[RoutePrefix("Dashboard"), Route("{action=index}")]
public class DashboardController : Controller
{
[Authorize, HttpGet, Route("~/")]
public ActionResult Index()
{
return View();
}
model Serene2.Common.DashboardPageModel
#{
ViewData["Title"] = "Dashboard";
ViewData["PageId"] = "Dashboard";
}
#section Head {
<link rel="stylesheet" href="~/Content/iCheck/flat/blue.css">
<link rel="stylesheet" href="~/Scripts/morris/morris.css">
<link rel="stylesheet" href="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet" href="~/Scripts/datepicker/datepicker3.css">
<link rel="stylesheet" href="~/Scripts/daterangepicker/daterangepicker-bs3.css">
<link rel="stylesheet" href="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<script src="~/Scripts/raphael/raphael-min.js"></script>
<script src="~/Scripts/morris/morris.min.js"></script>
<script src="~/Scripts/sparkline/jquery.sparkline.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<script src="~/Scripts/knob/jquery.knob.js"></script>
<script src="~/Scripts/daterangepicker/moment.min.js"></script>
<script src="~/Scripts/daterangepicker/daterangepicker.js"></script>
<script src="~/Scripts/datepicker/bootstrap-datepicker.js"></script>
<script src="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<script src="~/Scripts/adminlte/pages/dashboard.js"></script>
<script src="~/Scripts/adminlte/demo.js"></script>
}
#section ContentHeader {
<h1>#LocalText.Get("Navigation.Dashboard")<small>#Html.Raw(Texts.Site.Dashboard.ContentDescription)</small></h1>
}
<div class="inner">
<p>My Random Value From Controller</p>
</div>
hey with ajax you can easily achieve that,
The main issue is such approach will lead to infinite recursive loop so handle with care.Anyway your code should be like below
1.In cshtml
<p id="pValue"></p>
2. In script
var someRootPath = "#Url.Content("~")";
(function randomGenerator() {
$.ajax({
url: someRootPath + 'Dashboard/GetRandomValue',
success: function (data) {
$('#pValue').html(data.someValue);
},
complete: function () {
setTimeout(randomGenerator, 1000);
}
});
})();
and finally
3.Controller
[HttpGet]
public JsonResult GetRandomValue()
{
return Json(new { someValue = Guid.NewGuid().ToString() }, JsonRequestBehavior.AllowGet);
}
Hope this will help according to your current scenario.
If you want to refresh your page every second, you could put some javascript on the page like:
<script type="text/javascript">
setTimeout(function(){ document.location.reload(); }, 1000);
</script>
If you only want to update part of the page, you can make an ajax call (http://api.jquery.com/jquery.ajax/ or https://developer.mozilla.org/nl/docs/Web/API/XMLHttpRequest) which would point to your controller action - returning only the necessary data. Then, with javascript again, you can modify the parts of the page you find relevant.

Razor in Javascript

I don't know how to use razor syntax in Javascript.
I want to make Html.ListBoxFor with items from my model. I used to use:
#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })
As you see I want also use chzn-select class, to have better layout.
For now, I just have this code above in HTML as plain text, but I want have there things from my model.
Any ideas?
There is my code in ASP.NET MVC:
#model Generator.Models.ExamModel
#{
ViewBag.Title = "Generate";
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Multiple_chosen/chosen.jquery.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ListOfTags.js")" type="text/javascript"></script>
<script >
$(".chzn-select").chosen();
</script>
}
<link href="#Url.Content("~/Multiple_chosen/chosen.css")" rel="stylesheet" type="text/css" />
<h1>#ViewBag.Title</h1>
<h2>#ViewBag.Message</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Generate</legend>
<div class="editor-label">Numbers</div>
<div class="editor-field" id="NumberOfModels">
#Html.EditorFor(model => model.NumberOfQuestions)
</div>
<div class="editor-label">Tags</div>
<div id="itemsmodel"></div>
<br>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
And there is javascript file:
var models = document.getElementById("NumberOfQuestions");
var modelsTable = document.getElementById("itemsmodel");
models.addEventListener("change", drawModels, false);
function drawModels() {
var modelsNum = parseInt(models.value);
var curModels = modelsTable.childElementCount;
if (modelsNum > curModels) {
var delta = modelsNum - curModels;
for (var i = 0; i < delta; i++) {
var input = document.createElement("div");
input.className = "editor-field";
input.innerHTML = "#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = \"chzn-select\", data_placeholder = \"Tags...\" })";
modelsTable.appendChild(input);
}
} else {
while (modelsTable.childElementCount > modelsNum) {
modelsTable.removeChild(modelsTable.lastChild);
}
}
}
drawModels();
My ViewModel: ExamModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ExamGenerator.Models
{
public class ExaminationModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<int> TagIdList { get; set; }
public int NumberOfQuestions { get; set; }
public string Content { get; set; }
}
}
My ActionResult Generate() in controller:
public ActionResult Generate()
{
ViewBag.Tags = new MultiSelectList(genKolEnt.TAGS, "Id", "Name", null);
return View();
}
While you can generate HTML in Javascript using Razor, if the Javascript is in an MVC view, I find that injecting into JS leads to maintenance problems. You ideally want all your JS in separate files to allow for bundling/caching and the ability to break-point the JS code (which is harder in the view).
Either inject only simple things into JS on the page, or inject elements instead.
You can inject your template Razor list into a dummy script block, so you can extract the html from it later. The type="text/template" means the browser will ignore it e.g.:
<script id="ListTemplate" type="text/template">
#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })
</script>
The view page now looks like this (left out the irrelevant parts):
#section styles{
<link href="#Url.Content("~/Multiple_chosen/chosen.css")" rel="stylesheet" type="text/css" />
}
<h1>#ViewBag.Title</h1>
<h2>#ViewBag.Message</h2>
<script id="ListTemplate" type="text/template">
#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Generate</legend>
<div class="editor-label">Numbers</div>
<div class="editor-field" id="NumberOfModels">
#Html.EditorFor(model => model.NumberOfQuestions)
</div>
<div class="editor-label">Tags</div>
<div id="itemsmodel"></div>
<br>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Script now looks like this (jQuery version with JS as comments):
// ListOfTags.js file
// This is a shortcut DOM ready handler for $(document).ready(function(){ YOUR CODE HERE })
$(function () {
// Attach an event handler for the "change" event
$('#NumberOfQuestions').change(function () {
var $numberOfQuestions = $(this); // Convert current DOM element (the counter) to a jQuery element
var $modelsTable = $('#itemsmodel'); // document.getElementById("itemsmodel");
var modelsNum = ~~$numberOfQuestions.val(); // parseInt(models.value);
var curModels = $modelsTable.children().length; // modelsTable.childElementCount
var delta = modelsNum - curModels;
// While too few, add more
while (delta > 0) {
var $input = $('<div>').addClass('editor-field'); // document.createElement("div"); .className = "editor-field";
var template = $('#ListTemplate').html(); // Fetch the template from a script block (id="ListTemplate")
$input.html(template); // input.innerHTML =
$modelsTable.append($input); // modelsTable.appendChild(input);
delta--;
}
// While too many, remove the last
while (delta++ < 0) {
$modelsTable.children().last().remove(); // modelsTable.removeChild(modelsTable.lastChild);
}
}).change(); // Trigger an initial change event so it runs immediately
});
Notes/tips:
Place any JS in the page, at the bottom of the view, as it is easier to find. It does not matter where the #section Scripts is as the master page determines where it is injected on the final page.
Always use single quotes (') in Javascript constants by default, so that nested strings can be " which are more often required than 's. Just a good habit to get into. In fact if you had used them your code may have worked as you have added \ escaping to the quotes which will mess up the Razor processing
e.g.:
= '#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })';
If you add a #RenderSection("styles", required: false) to your master page(s) you can do the same thing for CSS as you do for scripts (ensuring all CSS is loaded in the header (for consistency). Just place them in a #section styles block.
e.g.
<head>
...
#Styles.Render("~/Content/css")
#RenderSection("styles", required: false)
...
</head>
~~ is a handy (and fast) alternative to parseInt to convert values to integers.
Use $ as a prefix for jQuery object variables. This makes it easier to remember when to use jQuery methods vs DOM properties.
Test controller code:
private MultiSelectList TagList()
{
var items = new List<KeyValuePair<int, string>>() {
new KeyValuePair<int, string>(1, "MVC"),
new KeyValuePair<int, string>(2, "jQuery"),
new KeyValuePair<int, string>(3, "JS"),
new KeyValuePair<int, string>(4, "C#"),
new KeyValuePair<int, string>(5, "PHP")
};
MultiSelectList list = new MultiSelectList(items, "key", "value", null);
return list;
}
// Get request starts with one list
public ActionResult Test()
{
ExamModel vm = new ExamModel()
{
NumberOfQuestions = 1,
TagIdList = new List<int>()
};
ViewBag.Tags = TagList();
return View(vm);
}
[HttpPost]
public ActionResult Test(ExamModel model)
{
ViewBag.Tags = TagList();
return View(model);
}
If it's a static JavaScript file and you are not generating it dynamically with razor view engine It won't work because in this case there is no processing performed on a server side. It is the same as accessing static html page/css file/image and etc...
On the other hand if this JavaScript is part of some Razor view, which means that it gets rendered by razor view engine, when you have return View() (or anything like that) in your controller action, than this code should work.
The problem is, java script files are not processed by server, so you won't be able to insert anything in those using ASP.NET MVC. Razor files on the other hand are processed on server so you can insert data into those (either through view bag or model).
One way is:
.cshtml:
<script>
var someVariable = '#model.data';
</script>
then use this variable in your javascript file:
function someFunction(){
var myData = window.someVariable;
}
The other way is to have all javascript in .cshtml file and render it as a partial view.
#Html.Partial("Path/to/javascript/in/razor/view")
edit: seeing your code, this will not help you very much.
If you want to dynamically add/remove dom elements, you will have to do it with javascript: either generate them with "document.createElement()" or load them via ajax if you want some server side processing.
#Html.ListBoxFor
is a server side helper that generates tag and fills it up depending on the parameters. You can do that with javascript as well.

how to access the current controller name inside my Razor view jquery

I have the following script , that is being used inside multiple views:-
$("#ChoiceTag, #ChoiceName").each(function () {
$(this).change(function () {
if ($("#ChoiceName").prop("checked")) {
$.getJSON("#Url.Content("~/Firewall/LoadCSName")",
function (CSData) {
var select = $("#GeneralCSID");
select.empty();
select.append($('<option/>', {
value: "",
text: "Select Name..."
}));
$.each(CSData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
select.val('#Model.CSIT360ID');
});
});
}
the script is exactly the same for all the views except for the controller name inside the following statement:-
$.getJSON("#Url.Content("~/Firewall/LoadCSName")",
so i am looking to move the above script and add it inside a separate .js file, and then reference this script , but i have the following two question:-
if i move the script to the script folder i need to dynamically reference the current controller name to build the URL, so is this possible
can i still reference the viewbag as i am currently doing ..
Thanks
If you move your Javascript into an external file you can't use your Razor syntax. Therefore, #Url.Content("~/Firewall/LoadCSName") will not resolve.
To overcome this add this to your view
<script type="text/javascript"> var AppPath = '#Url.Content("~/")'</script>
and reference it in your script like this
$.getJSON(AppPath + "Controller/Action")
Regarding the viewbag. Just put the viewbags value in a variable as shown above and your external file can reference it.
Hope this helps
Update
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
var AppPath = '#Url.Content("~/")';
var SomeValue = '#Model.CSIT360ID';
var ControllerName = "Firewall/LoadCSName";
</script>
<!--Move this to an external File-->
<script type="text/javascript">
$("#ChoiceTag, #ChoiceName").each(function () {
$(this).change(function() {
if ($("#ChoiceName").prop("checked")) {
$.getJSON(AppPath + ViewBagValue), function(CSData) {
var select = $("#GeneralCSID");
select.empty();
select.append($('<option/>', {
value: "",
text: "Select Name..."
}));
$.each(CSData, function(index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
select.val(SomeValue);
});
//end each
});
}
});
</script>
</body>
</html>
Update 2
This is how you could reference the controller in the url.content
<script type="text/javascript">
var AppPath = '#Url.Content("~/" + HttpContext.Current.Request.RequestContext.RouteData.Values["controller"])'
</script>
you can get the controller name this way:
#{
string controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
}
To access controller name from view use
#{
ViewContext.RouteData.Values["controller"].ToString();
}
To access controller instance one can use as follow
#{
(HomeController)ViewContext.Controller
}
One (slightly hacky) to make the current controller name accessible to JS would be to burn it into a global or namespaced variable assignment in the layout.
<script>
var app = window.app || {}
app.currentController = "#HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString().toLower()";
</script>
Alternatively, a common way I work is to add classnames of the current controller and action to the body tag, to assist in DOM based routing in any javascript.

getting null in file value passed from jquery-ajax in struts2 action class

i've wrote a code for uploading file from jsp to mysql database using jquery-ajax on selecting a file from file browser. on selecting a file the JavaScript passes the file and id as parameter to action class, but i'm getting null value for the file in action class.
can anyone please tell me how to solve this problem.
index.jsp
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script>
function filebrowse(toolid){
document.getElementById("toolidforimg").value=toolid;
$("#filetochange").trigger('click');
return false;
}
function changeFile(var3)
{
var param="filetochange="+(document.getElementById("filetochange").value)+"&toolidforimg="+document.getElementById("toolidforimg").value;
var resultStringX = $.ajax({
type: "POST",
url:"getFileChange.action",
enctype: 'multipart/form-data',
data: param,
async: false
}).responseText;
resultStringX=$.trim(resultStringX);
return false;
}
</script>
</head>
<body>
<s:hidden value="" name="toolidforimg" id="toolidforimg"/>
Change File
<input style="opacity:0;" type="file" onchange="changeFile(this.value)" id="filetochange" name="filetochange" >
</body>
</html>
struts.xml
<action name="getFileChange" class="com.MyactionClass" method="getFileChange">
<result name="success">browseFiles.jsp</result>
</action>
MyactionClass.java
class MyactionClass
{
File filetockhange;
String toolidforimg;
public File getFiletochange() {
return filetochange;
}
public void setFiletochange(File filetochange) {
this.filetochange = filetochange;
}
public String getToolidforimg() {
return toolidforimg;
}
public void setToolidforimg(String toolidforimg) {
this.toolidforimg = toolidforimg;
}
public String getFileChange()
{
HERE I AM GETTING filetochange VALUE AS NULL
return SUCCESS;
}
}
Put an HTML Form element around the fields you want to send (File, Hidden, etc).
That should be enough.
Some hints:
always specify a DTD, or you will fall in the odd world of the Quirks Mode. In your case, the HTML5 DTD should fit because you can upload files through AJAX only with HTML5: change <html> with <!DOCTYPE html>
always use Struts2 Tags instead of HTML tags when possible, like <s:form>, <s:file> and <s:a>.
only the accessors (getters) should begin with get, not other methods and for sure not an Action name;

Generate javascript file on the fly in asp.net mvc

Friends,
I am trying to use DyGraph in my application. Please look at the code below -
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
<title>crosshairs</title>
<script type="text/javascript" src="dygraph-combined.js"></script>
<script type="text/javascript" src="data.js"></script>
</head>
The code uses data.js file containing function to get some static data.
I want data.js to be generated using a controller method so that it will generate data using database.
Can anybody help me out to resolve this issue.
Thanks for sharing your valuable time.
You could define a controller action:
public ActionResult Data()
{
// Obviously this will be dynamically generated
var data = "alert('Hello World');";
return JavaScript(data);
}
and then:
<script type="text/javascript" src="<%= Url.Action("Data", "SomeController") %>"></script>
If you have some complex script that you don't want to generate in the controller you could follow the standard MVC pattern by defining a view model:
public class MyViewModel
{
... put required properties
}
a controller action which would populate this view model and pass it to the view:
public ActionResult Data()
{
MyViewModel model = ...
Response.ContentType = "application/javascript";
return PartialView(model);
}
and finally a view which in this case will be the javascript representation of the view model (~/Views/SomeController/Data.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MyViewModel>" %>
alert(<%= new JavaScriptSerializer().Serialize(Model.Name) %>);
Full Disclosure
This answer is copy/pasted from another question:
Dynamically generated Javascript, CSS in ASP.NET MVC
This answer is similar to other answers here.
This answer uses cshtml pages rather than ascx controls.
This answer offers a View-Only solution rather than a Controller-Only solution.
I don't think my answer is 'better' but I think it might be easier for some.
Dynamic CSS in a CSHTML File
I use CSS comments /* */ to comment out a new <style> tag and then I return; before the closing style tag:
/*<style type="text/css">/* */
CSS GOES HERE
#{return;}</style>
Dynamic JS in a CSHTML File
I use JavaScript comments // to comment out a new <script> tag and then I return; before the closing script tag:
//<script type="text/javascript">
JAVASCRIPT GOES HERE
#{return;}</script>
MyDynamicCss.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
}
/*<style type="text/css">/* */
#foreach (var field in fieldList) {<text>
input[name="#field"]
, select[name="#field"]
{
background-color: #bbb;
color: #6f6f6f;
}
</text>}
#{return;}</style>
MyDynamicJavsScript.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);
}
//<script type="text/javascript">
$(document).ready(function () {
var fieldList = "#Html.Raw(fieldArray)";
var fieldArray = fieldList.split(',');
var arrayLength = fieldArray.length;
var selector = '';
for (var i = 0; i < arrayLength; i++) {
var field = fieldArray[i];
selector += (selector == '' ? '' : ',')
+ 'input[name="' + field + '"]'
+ ',select[name="' + field + '"]';
}
$(selector).attr('disabled', 'disabled');
$(selector).addClass('disabled');
});
#{return;}</script>
No Controller Required (using Views/Shared)
I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:
<style type="text/css">#Html.Partial("MyDynamicCss")</style>
<script type="text/javascript">#Html.Partial("MyDynamicJavaScript")</script>
Using a Controller (optional)
If you prefer you may create a controller e.g.
<link rel="stylesheet" type="text/css" href="#Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="#Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>
Here's what the controller might look like
MyDynamicCodeController.cs (optional)
[HttpGet]
public ActionResult MyDynamicCss()
{
Response.ContentType = "text/css";
return View();
}
[HttpGet]
public ActionResult MyDynamicJavaScript()
{
Response.ContentType = "application/javascript";
return View();
}
Notes
The controller version is not tested. I just typed that off the top of my head.
After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml #{return;}, but I haven't tried it. I imagine it's a matter of preference.
Concerning my entire answer, if you find any syntax errors or improvements please let me know.

Categories

Resources