I have a script file, script.js that holds all the javascript for a given page. In there, I do some ajax POST methods and generate an HTML view from the response. There are certain buttons that I want to be shown if the current user is an admin / hidden if the current user is not an admin.
How can I add Razor syntax in success: function () {}; to display / hide those buttons?
You're looking for RazorJS.
Just wanted to add to SLaks' answer a few more details that made it hard for me to use RazorJS.
After installing it with the Package Manager as explained here, you should add in your razor view the following line:
#Html.RazorJSInclude("~/Scripts/my_javascript_file.js")
And then all your razor code will work just fine!
Related
I currently have a js file that gets loaded with a page.
Now that .js file has the following statement in it
$("#Click").on('click', function () {
__CHILD_WINDOW_HANDLE = window.open('MyPopUp.html', '_blank', 'width=700,height=500,left=200,top=100');
});
From the above statement when the user clicks on the "Click" button a child window (MyPopUp.html) should load up , however I get the error
The resource cannot be found.
My question is how do I specify the path of the html file ? The only way I am familiar with is through RouteConfig.cs in which Ill need to introduce another controller. Any suggestions on how I can accomplish this ?
I solved this issue by creating a separate controller and then having that controller return the html file. Also since I am using razor html files are not allowed so I had to return back a cshtml file.
I am building a .NET MVC 5 application on back-end and Angularjs on front-end.
I am loading .cshtml views in a div containerOne on a parent .cshtml page with ui.router and everything is working fine. An issue I would like to solve is when I enter manually a page URL that is C# controller's action path(in the example I provided below it is /Proposal/Customers) - my view is loaded on a whole page. What I want to be called is a .state named 'customers' in my example, or something like that. My example code is(part of my proposalConfig.js):
.state('customers', {
url: 'AllCustomers',
views: {
containerOne": {
templateUrl: '/Proposal/Customers'
}
}
});
On my back-end I have a ProposalController.cs and an action method Customers that calls a Customers.cshtml view.
Anyone has an idea how to solve this?
EDIT
The same thing happens if, instead of 'AllCustomers' I put '/Proposal/Customers', and then after the first load of a .state I refresh a page.
I forgot to mention that I have $locationProvider.hashPrefix('!').html5Mode(true); in a proposalConfig.js file.
If you mean that the entire page html markup (html tag, body tag and such)is being returned when you only want the specific content of the Customer.cshtml, which I also assume only has what you want in it, its probably because your view has a shared view start layout. Put this in Customer.cshtml
#{
Layout = null ;
}
I am trying to get Razor (C#) and javascript to play nicely together but I can't seem to do it. I have searched the other articles on StackOverflow, but none of them seem
to work for me.
Some noticeable differences from other posts and mine include the following:
I am using an external JavaScript file (not mandatory, but it is there).
I am using a cshtml file for the header layout for all pages (which puts the head tag in a different file than the one actually attempting to call the function.
I also use jQuery, if it would be easier that way.
What I am trying to accomplish:
All I need to do is get the contents of a tag (innerHTML, or .html in jQuery) (by id, class, whatever) and assign that value to "AppState["gEntryID"] for use with the next page.
Some things I have tried:
function entryClickHandler()
{
#AppState["gEntryID"] = document.getElementById("tester").innerHTML;
}
AND
function entryClickHandler()
{
<text>
#AppState["gEntryID"] = document.getElementById("tester").innerHTML;
</text>
}
I have tried these (and a few other variations on these) in both the external file and the head section within the HeaderLayout File.
I understand that C# runs before the page and the JavaScript mostly runs after the page (at least with events such as this).
Any help would be greatly appreciated.
It doesn't work that way. You cannot set variables in the C#/Razor side with JavaScript without using a form post or ajax submit.
Javascript doesn't get access to the page until after Razor has done it's part and rendered and sent the page.
I have many HTML helper in Helpers.cshtml file, but some of the helper (html) need some jquery action, so how do i can call jquery inside helpers.cshtml, is that possible?
i know we can keep the js file in header or particular page, but i do not want to do like that, i want to use jquery or javascript only on the page which loaded particular helper.
anyone have idea on this?
My scenario is, i have list box control, that is properly loading from helper, but i need to apply custom theme to the list box.
Little more Clarity
//in index.cshtml
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
//in Helpers.cshtml
#helper testListBox(string listName, string listData){
//...... HTML code .........
//Javascript here?
}
With Web Forms, the framework could automatically include Javascript (once) when certain server controls were used on a page; ASP.Net MVC has no such facility. It sounds like this is what you're missing.
The way to do it is on the client. Look at RequireJS at http://requirejs.org/. This is a client-side library for managing Javascript dependencies. This does what Web Forms did, but better, and it does more. Your master layout will have a script tag like this:
<script src="/Scripts/require.js" type="text/javascript" data-main="/Scripts/main"></script>
This can be the only script tag you include on every page. Everything else can be dynamically loaded only as needed by RequireJS. It's true that you load this on every page, but it's smaller than jQuery, and it earns its place because it does so much for you.
Using your example, let's say you have this markup:
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
and it renders HTML and needs jQuery scripting. You would render this:
// HTML for list box here
<script type="text/javascript>
require(['jquery'], function($) {
// Do your jQuery coding here:
$("myList").doSomething().whatever();
});
</script>
The require function will load jQuery, unless it has already been loaded, and then execute your code. It's true that your jQuery snippet is repeated once per use of the HTML helper, but that's not a big deal; that code should be short.
RequireJS manages dependencies effectively; you can have module A, and module B which dependes on A, and module C which depends on B. When your client code asks for module C, A and B will be loaded along with C, and in the correct order, and only once each. Furthermore, except for the initial load of require.js, scripts are loaded asynchronously, so your page rendering is not delayed by script loading.
When it's time to deploy your site on the web server, there's a tool that will examine the dependencies among the Javascript files and combine them into one or a small number of files, and then minimize them. None of your markup has to change at all. While in development, you can work with lots of small, modular Javascript files for easy debugging, and when you deploy, they are combined and minimized for efficiency.
This is much better than what the web forms framework did, and entirely client-side, which in my opinion is where it belongs.
You can put a <script> tag in the helper body.
How about this for an example of a partial view:
#model Member.CurrentMemberModel
#{
var title = "Test View";
}
<script type="text/javascript">
// Javascript goes in here, you can even add properties using "#" symbol
$(document).ready(function () {
//Do Jquery stuff here
});
</script>
#if (currentMember != null)
{
<div>Hello Member</div>
}
else
{
<div>You are not logged in</div>
}
I'm currently working on a project where I need to use a lot of AJAX AutoCompleteExtenders, and they have been working fine- but now I'm tidying up the code and implementing a master page, I'm running into issues. I have this JS:
$find('txtName')._onMethodComplete = function(result, context) {
$find('txtName')._update(context, result, false);
webservice_callback(result,context);
};
And when I load the page, this error occurs relating to that snippet:
Microsoft JScript runtime error: 'null' is null or not an object
Just to reiterate, this only happens when I have a master page for some bizarre reason. Any ideas?
You need to use <%=txtName.ClientID%> because with master pages in use your ids will be mangled to avoid namecollision between masterpage and aspx/usercontrols etc.
However please note that to be able to use <%= you will have to include the JS in the ASP.NET markup code. This can be done with the IIS #include rather than using script's src.
Example:
<!-- #Include virtual=".\JS\YourJSFileWithASPNETMarkup.js" -->
Try View Source on your page and make sure that the <input> is still named txtName. Sometimes with master pages, the name changes.
Can you try this:
('<%=txtName.ClientID>')._onMethodComplete = function(result, context) {
If you're using .NET 4 then you could add ClientIDMode="Static" into the page directive, which would tell ASP.NET to keep it's mucky hands off the element IDs.
When you use masterpage, the ID of your controls change, so you can't use the same ID in Javascript, instead you can modify your selector like this : $('input[id*="txtName"]') now it finds all the controls which have an id that contains txtName. there are different selectors of this kind that you can use.
here is a useful link