I got an action result inside a controller and i need to display Modals from bootstrap-modal the problem is... .
ScriptManager.RegisterStartupScript isn't working like in old asp.net
there is a solution to this? I'm new to mvc.
Ok, the easiest solution for registering javascript from the controller was quite obvious, but frustrating for someone who's new to the pattern:
Using named sections we find a place for put the javascript
You can use [Named Sections][1].
_Layout.cshtml
<head>
<script type="text/javascript" src="#Url.Content("/Scripts/jquery-1.6.2.min.js)">
#RenderSection("JavaScript", required: false)
</head>
and this code for the view
_SomeView.cshtml
#section JavaScript
{
#Html.Raw(ViewBag.message)
}
and in the controller we return
ViewBag.message = #"<script type='text/javascript' language='javascript'>alert(""Hello World!"")</script>"; ;
In ASP.NET MVC scripts are not registered in controller actions. There's a separation between controllers and views. So you could directly put the script in the corresponding view:
Related
How can I insert javascript in asp.net MVC application(view)?
I am doing following things in my javascript:
1) Read values from DOM elements.
2) Send data to Controler action method from Jquery Ajax.
3) Validating my input.
4) Read/Write cookies
How can I insert javascript in View.
Should it be something like this?
<script src="../Scripts/Jquery-2.1.js" type="text/javascript"></script>
<script src="../Scripts/jquery.cookie.js" type="text/javascript"></script>
<script>
$(document).ready(function ()
{
$.cookie("pc", "Navada, US");
}
);
</script>
#{
ViewBag.Title = "ViewPage1";
}
<h2>ViewPage1</h2>
Thanks for your answer
Not sure if i understand your question right, but if so you may need to put your script tags into the head tag.
To be able to put your custom js things into head you could try looking at this example:
In your _Layout page add this between <head></head>:
#RenderSection("CustomScripts", required: false);
And on your page:
#section CustomScripts
{
<script src="#Url.Content("~/Scripts/foo.js")" type="text/javascript"></script>
}
EDIT: as #Liam correctly pointed out that the _Layout file could be in any other path, #StephenMuecke's clarification applied.
I'm writing an ASP.NET application with AngularJS. I have a value that can only be accessed from the codebehind of a page. I'd like to pass this value down so it can be used by an AngularJS controller. I know it's possible to grab URL parameters for use in AngularJS, but I haven't been able to find any other way of getting a value into my controller. Is this possible?
For example, if I have a setup like this:
<%= user.UserDescription %> <%-- this is how I'd get my value from the codebehind --%>
<div ng-app='myApp' ng-controller='myController1'></div>
...
</div>
I want myController1 to have access to user.UserDescription. It's obviously possible to place the value anywhere on the page, by embedding the C# in the ASP.NET page as you see above, but is it possible to pass it into the controller?
I had a similar issue as I had sever side config that I wanted the client side application to know. The solution I came up with is was a config constant that I would add to the bottom of the page. Then loaded that into my services, etc....
Something like this
<html>
<head>
....
</head>
....
<body>
<script>
(function(){
'use strict';
angular.module('myapp.config',[])
.constant('CONFIG', {
user: {
description: '<%= user.UserDescription %>'
}
});
})();
</script>
</body>
</html>
Fairly new to Angular and working inside of an existing code base.
Basically, there's an element that exists within the root document (index.html) that already exists in the html before the Angular library loads. Because of this, the ng-click directive isn't registered.
Is there an easy way that I can pass Angular a reference to the element in question and have it register that as one of its own?
Sample code (obviously missing parts, just to illustrate Angular loads after):
<html>
<body ng-app="allMyCookiesApp">
<a ng-click="giveGeuisACookie()">GIMME</a>
<script src="angular.js"></script>
</body>
</html>
I'd like to get a cookie when I click GIMME.
ng-app will bootstrap everything inside it once angular loads. This includes compiling and linking the ng-click in your example. So I think the real problem may be elsewhere.
The biggest omission from this example is any controller. I expect you are missing a controller that can place the giveGeuisACookie method on the correct scope to be used by ng-click. For example
angular.module('allMyCookiesApp', [])
.controller('geuisCtrl', function($scope) {
$scope.giveGeuisACookie = function() {
// Cookie time
};
});
would define your module for ng-app and register a controller for it. This controller will add the giveGeuisACookie function to its scope.
<html>
<body ng-app="allMyCookiesApp" ng-controller="geuisCtrl">
<a ng-click="giveGeuisACookie()">GIMME</a>
<script src="angular.js"></script>
</body>
</html>
tells angular to use the controller so that ng-click will have access to the correct method.
If this is not the problem it may be worth adding a jsfiddle with a working (or not) example of what you are doing.
I just started this HTML5 project where we decided to make it a single page architecture by leveraging jQuery $.load() method. Unfortunately, as soon as the JS started to grow, we quickly started running into issues where the modules loaded into the master dashboard have no knowledge of their parent.
The architecture looks like this:
dashboard.html (master file)
moduleA.html
moduleA.js
moduleB.html
moduleB.js
moduleC.html
moduleC.js
Since we decided to also keep the JS as separate files, we are having to load all JS files through dashboard.html in order to invoke them individually when modulex is loaded.
So when loading moduleA.html into the dashboard we have to call its corresponding JS. To do this we simply wrote the JS using a Module Pattern so we can easily invoke it by doing a function call, like:
<script>
moduleA
</script>
or this if we want to access a specific property of this member.
<script>
moduleA.someMethod();
</script>
Now, I know there are is gotta be a nicer way of doing this, right? I hate having to have script tags in the HTML modules in order to load its corresponding JS file.
Another limitation of this is the fact that we no longer can work on modules individually, since the scripts and CSS invocation happens on the parent (dashboard.html) so certainly when moduleA.html is loaded directly, it is pure HTML with no script or CSS.
I looked through the other questions but I didn't see anyone with the same problem.
I looked at AngularJS, EmberJS, KO.JS and BoilerPlateJS but none of them addresses what we are trying to accomplish. The only one that has a similar single page concept is jQuery Mobile but I don't know if you can switch from jQuery to jQuery Mobile and everything remains working.
Has anyone face this issue yet? Is there a solution or would I have to go with a custom solution.
Thanks!
I could argue about AngularJS with you. It is exactly what you need
dashboard.html is layout with some directives attached, but power lies in AngularJs if you use ng-view directive
here is example:
dashboard.js
var app = angular.module("modularApp",[]);
app.config(['$routeProvider', "$locationProvider", function routes($routeProvider, $locationProvider) {
$routeProvider.when('/dashboard', {
controller:'HomeCtrl',
templateUrl:'templates/home.html'
});
$routeProvider.when('/moduleA', {
controller:'ModuleACtrl',
templateUrl:'templates/moduleA.html'
});
$routeProvider.when('/moduleB', {
controller:'ModuleBCtrl',
templateUrl:'templates/moduleB.html'
});
$routeProvider.otherwise({redirectTo: "/dashboard"});
}]);
templates/dashboard.html
<html ng-app="modularApp">
<head>
<!--.... include angular minified js file and what else you need...-->
<script type="text/javascript" src="dashboard.js"></script>
<script type="text/javascript" src="moduleACtrl.js"></script>
<script type="text/javascript" src="moduleBCtrl.js"></script>
</head>
<body>
<a ng-href="#/moduleA">Open Module A View</a>
<a ng-href="#/moduleB">Open Module B View</a>
<!-- Add widgets header menus .... -->
<ng-view></ng-view>
</body>
</html>
moduleACtrl.js
var app=angular.module("modularApp");
app.controller("ModuleACtrl",function($scope){
$scope.scopeValue="Hellow from view";
});
moduleBCtrl.js
var app=angular.module("modularApp");
app.controller("ModuleBCtrl",function($scope){
$scope.scopeValue="Hellow from another view";
});
templates/moduleA.html
<div>{{scopeValue}} in module A</div>
templates/moduleB.html
<div>{{scopeValue}} in module B</div>
You can do more complex things with angular then just this. All depends on your needs. Do you have any special requirements :)
Also, you could create your own directive, like ng-view and use your own $route service and $routeProvider so you can add css and javascript you want to dynamically load when some rute match url.
so instead of above routing table, you could have
app.config(['$myRouteProvider', "$locationProvider", function routes($routeProvider, $locationProvider) {
$routeProvider.when('/dashboard', {
javascript:'javascript/dashboard.js',
templateUrl:'templates/dashboard.html',
cssfile: 'css/dashboard.css'
});
$routeProvider.when('/moduleA', {
javascript:'javascript/moduleA.js',
templateUrl:'templates/moduleA.html',
cssfile: 'css/moduleA.css'
});
$routeProvider.when('/moduleB', {
javascript:'javascript/moduleB.js',
templateUrl:'templates/moduleB.html',
cssfile: 'css/moduleB.css'
});
$routeProvider.otherwise({redirectTo: "/dashboard"});
}]);
But that is, pardon on my French, stup. There are couple libs I tried in ruby on rails to acheive similar, but backend is rendering content, or just part of content. But I'm not sure which backend you are using and are you interested to switch to rails anyway.
DomController in BoilerplateJS does what you need, without using any custom HTML attributes. Your dashboard.html can just have place holders where you want to inject your components. I'm just pulling out some html below from BoilerplateJS index.html to show how it works:
<body>
<section id="page-content">
<header>
<section class="theme"></section>
<section class="language"></section>
</header>
<aside>
<section class="main-menu"></section>
</aside>
</section>
</body>
theme, language and main-menu sections above are just place holders in to which relavant components would be injected by the DomController. The DomController can be now used to register the components with appropriate selectors as below:
//scoped DomController that will be effective only on $('#page-content')
var controller = new Boiler.DomController($('#page-content'));
//add routes with DOM node selector queries and relavant components
controller.addRoutes({
".main-menu" : new MainMenuRouteHandler(context),
".language" : new LanguageRouteHandler(context),
".theme" : new ThemeRouteHandler(context)
});
controller.start();
Above code is extracted from "/boilerplatejs/src/modules/baseModule/module.js"
I have been building my first ASP.NET MVC web app. I have been using the jQuery autocomplete widget in a number of places like this:
<head>
$("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
</head>
The thing is I have this jQuery code in a number of different places through my web app. So i thought I would create a seperate javascript script (script.js) where I could put this code and then just include it in the master page. Then i can put all these repeated pieces of code in that script and just call them where I need too. So I did this. My code is shown below:
In the site.js script I put this function:
function doAutoComplete() {
$("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
}
On the page I have:
<head>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/site.js" type="text/javascript"></script>
<script type="text/javascript">
doAutoComplete();
</script>
</head>
But when I do this I get an Invalid Argument exception and the autocomplete doesnt work. What am I doing wrong? Any ideas?Do i need to pass something to the doAutoComplete function?
The <%= will not be evaluated in your external javascript.
Solution: pass the URL as a parameter to your javascript function.
<script>
doAutoComplete('<%= Url.Action("Model", "AutoComplete") %>');
</script>
function doAutoComplete(url) {
$("#model").autocomplete({ source: url });
}
You need to put the function call in a script block, and make sure jquery is loaded before your site.js ...
<head>
<script src='path/to/jquery.js'></script>
<script src="../../Scripts/site.js" type="text/javascript"></script>
<script>
doAutoComplete();
</script>
</head>
EDIT:
Maybe the '<%= ... =%>' tag isn't being evaluated server-side, before the function gets sent to the browser? Here is an article on this: http://www.west-wind.com/weblog/posts/252178.aspx
Here is a quote from the post:
There's also a problem if you need
access to the [ASP.NET] variables in
.js files - you can't embed script
tags into a .js file so getting a
dynamic value into a static file is
problematic