Using Razor View Engine within JavaScript - razor

Using the new ASP.NET MVC 3.0 Razor View Engine, is there any way to call upon it within javascript code?
In the normal view engine, you could do something like ...
<script type="text/javascript">
$(document).ready(function() {
function somejQueryFunction(obj) {
<%= obj.ExecuteSomething() %>
}
});
</script>
But I cannot find any way to do similar with Razor.

The following should work:
<script type="text/javascript">
$(document).ready(function() {
function somejQueryFunction(obj) {
#obj.ExecuteSomething()
}
});
</script>
Basically any time you have <%: Expression %> or <%= Expression %> you can replace it with #Expression

Related

how to inject javascript at header and body using gulp

I want to inject javascript library inside head tag and my customized and my own code at body using GULP.
For Example:
<html>
<head>
<!-- injectJS -->
<script src="jquery.js">
<script src="d3.js">
<!-- injected -->
</head>
<body>
<!-- injectJS -->
<script src="index.js">
<!-- injected -->
</body>
</html>
I've been using gulp-template to do exactly this. Your index.html would then have to be adjusted. e.g.:
<% scripts.forEach( function ( file ) { %>
<script type="text/javascript" src="<%= file %>" inline></script>
<% }); %>
In this example your gulpfile task would look something like:
gulp.task('index', () =>
gulp.src('src/index.html')
.pipe(template({scripts: ['script.js', 'another-one.js']}))
.pipe(gulp.dest('dist'))
);
Another way to achieve this would be using gulp-inject. I prefer gulp-template though.

Query data from mongoose and display it on a html page

This is my schema
var productSchema = new mongoose.Schema({
name: String,
description: String
});
var Product = mongoose.model('Product', productSchema);
In my index.js i am using
exports.welcome = function(req,res) {
Product.find({},{},function(err,docs) {
res.render('welcome', {
"productlist" : docs
});
});
};
In my app.js i am calling this statement where routes is my variable to call welcome in index.js
app.get('/welcome',routes.welcome);
My schema is also written in index.js. What i want to do is display all the products with their name and description in my html page named "welcome.html".
Can anyone tell me like what should i write in my html page to do this.
From your latest comment, it means you are using EmbeddedJS as templating engine. Your answer is well documented here.
For complicity, an example of welcome.html to display results is:
<!DOCTYPE html>
<html>
<head>
<title>My Products</title>
</head>
<body>
<ul>
<% for(var i=0; i<productlist.length; i++) {%>
<li><%= productlist[i].name %> : <%= productlist[i].description %></li>
<% } %>
</ul>
</body>
</html>

Typeahead twitter bootstrap not functioning mvc4

I am trying to implement this code here
but I get no results while running the project.
here is my code:
View:
<input type="text" name="names" value="" id="typeahead" data-provide="typeahead" autocomplete="off" />
Again on view (index.cshtml):
<script type="text/javascript">
$(function () {
$('#typeahead').typeahead({
source: function (term, process) {
var url = '#Url.Content("~/index/GetNames")';
return $.getJSON(url, { term: term }, function (data) {
return process(data);
});
}
});
})
</script>
Controller (indexController.cs):
[HttpGet]
public JsonResult GetNames(string term)
{
// A list of names to mimic results from a database
List<string> nameList = new List<string>
{
"Jonathan", "Lisa", "Jordan", "Tyler", "Susan", "Brandon", "Clayton", "Elizabeth", "Jennifer", "Hadi"
};
var results = nameList.Where(n =>
n.StartsWith(term, StringComparison.OrdinalIgnoreCase));
return new JsonResult()
{
Data = results.ToArray(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
here are also the js scripts added at the end of the view page:
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery-1.9.1.intellisense.js"></script>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
here is also the list of bugs I get on runtime:
Uncaught TypeError: undefined is not a function bootstrap.js:29
Uncaught ReferenceError: intellisense is not defined jquery-1.9.1.intellisense.js:1
Uncaught TypeError: Object [object Object] has no method 'typeahead'
Please let me know what am i doing wrong!
This may be a bit old but you cannot use source: you must use either remote:, prefetch:, or local: as the error reads.
Which version of bootstrap are you using? The standalone plug-in no longer supports all of the different data providers in the same way as the old one did
First off, make sure you place the script tag referencing jquery first, before bootstrap. Also only load a single jquery script tag.
Like this:
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
All the JS libraries you are using at the moment have one dependancy: jQuery so they need to be loaded in right order:
<!-- jQuery should always be the first -->
<!-- jquery-1.9.1.js and jquery-1.9.1.min.js are the same but .min version is minified and always lighter, so use it for faster page load -->
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<!-- Any other library should be loaded after jQuery -->
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/jquery-1.9.1.intellisense.js"></script>
Hope this helps ;)

Conditionally execute JavaScript in Razor view

I'd like to execute a piece of JavaScript when a certain condition is true in my view model:
<script type="text/javascript">
#if (Model.Employees.Count > 1)
{
executeJsfunction();
}
</script>
This code doesn't compile, how should I do this?
Try with this:
<script type="text/javascript">
#if (Model.Employees.Count > 1)
{
#:executeJsfunction();
}
</script>
Note the "#:"
For multi-line script within the razor conditional block, you can use:
<script type="text/javascript">
#if (Model.Employees.Count > 1)
{
<text>
executeJsfunctionOne();
executeJsfunctionTwo();
executeJsfunctionThree({
"var_one": true,
"var_two": false
});
</text>
}
</script>
This can make it cleaner and more practical than adding #: to each line. Everything within the <text></text> blocks is rendered as script.
If you have more complicated JS, you can do the following (script tags, or any tags, within an #if don't need extra escaping):
#if (Model.Employees.Count > 1)
{
<script type="text/javascript">
$(function() {
executeJsfunction();
});
</script>
}
Use js if-else block, not C#. Js has its own if-else block.
<script type="text/javascript">
if (#Model.Employees.Count > 1)
{
executeJsfunction();
}
</script>
The MVC variables are processed on the server side, the code is always trying to render the Javascript values in order to generate the HTML, please try the code below :
<script type="text/javascript">
#{if (Model.Employees.Count > 1)
{
#:executeJsfunction();
}
}
</script>
I hope this helps.
I know this question posted while ago however I added a new solution as an alternative solution:
you can inject your value from the model into data attribute of selected DOM's element and validate your condition by checking the value of the same data attribute you injected while building your view.
for example, check the following view and the script code snippet how to do it:
<div id="myDiv" data-count="#Model.Employees.Count">
</div>
<script>
if($("#myDiv").data("count") > 1){
executeJsfunction();
}
</script>
In case if you don't want to even render the java script based on some condition
define a section in your layout html
<html>
<body>
#RenderSection("xyz", required: false)
</body>
</html>
in your view
#if (Model.Condition)
{
#section xyz{
<script>
$(function () {
// Your Javascript
});
</script>
}
}
In my case I don't want to expose my Javascript if that feature is not enabled, also it'll reduce the size of the page

UpdatePanel + jquery using on()

I've been experiencing the famous problem of jQuery not functioning after a postback. So I've done some research and the best new way is the live() function by jQuery. But turns out this one has been deprecated since version 1.7 and replaced with on() function.
So I transformed my jQuery plugin to use the on() function, but it still doesn't work after postbacks.
The plugin:
$(document).ready(function () {
$('.drag').on("mouseover", function () {
AfterPostBack();
$(this).draggable()
.click( function () {
$(this).draggable({ disabled: false });
}).dblclick( function () {
$(this).draggable({ disabled: true });
});
});
$('.text_label').on("blur",function () {
$(this).removeClass('focus');
});
});
var AfterPostBack = function () {
$('.drag').draggable("option", "containment", 'parent');
$('.drag').draggable("option", "snap", 'parent');
$('.drag').draggable("option", "cursor", 'move');
};
The web page:
<script type="text/javascript" src="Scripts/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui-1.8.23.custom.min.js"></script>
<script type="text/javascript" src="Scripts/myplugin.js"></script>
<link href="Styles/myplugin.css" rel="stylesheet" type="text/css" />
<asp:UpdatePanel runat="server" ID="UP1" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:Button ID="btn_AddText" runat="server" Text="Add Text" OnClick="AddText" />
<asp:PlaceHolder ID="ph1" runat="server">
<div class="drag">
<asp:Label ID="lbl1" class="text_label" runat="server" Text="Click Me"/>
</div>
</asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn_AddText" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Would love some help on this.
Thanks.
You can use function pageLoad(sender, args) { } instead of $(document).ready()
Instead of targeting browser-specific optimizations, the ASP.NET AJAX pageLoad() shortcut function is called as a result of a more uniform process.
That process is queued up the same way on all browsers, via a call to setTimeout with a timeout of 0 milliseconds. This trick leverages JavaScript’s single-threaded execution model to (theoretically) push the init event back until just after the DOM has finished loading.
Counter-intuitively, this isn’t the only point at which pageLoad() is called. It is also called after every partial postback. It basically functions as a combination of Application.Init and PageRequestManager.EndRequest.
source: https://encosia.com/document-ready-and-pageload-are-not-the-same/
there are 2 events add_init and document.ready run same time ones per page refresh
and the second is pageload that triggered every async postback ,but not triggered on first load
I made 3 functions and put the code where its relevent
Sys.Application.add_init(function () {
// Initialization code here, meant to run once.
try {
//doOnes();
doAllways();
} catch (e) {
console.log('Sys.Application.add_init: ', e);
}
});
$(document).ready(function () {
console.log('document.ready');
//doAllways();
}
function pageLoad() {
console.log('pageLoad');
//doAftrerAjax();
doAllways();
}
function doOnes() {
console.log('doOnes');
}
function doAftrerAjax() {
console.log('doAftrerAjax');
}
function doAllways(){
console.log('doAllways');
AfterPostBack(); <---this the place for the code
}
`