Angular 2 and C#/.NET - c#

I know you can use C# and .NET with Angular 2, but I've only seen it done in the layouts. Can you include C# in the component files? For example, there is a dashboard.component.html file in the Tour of Heroes tutorial on the Angular 2 website. Could you change that to dashboard.component.cshtml and include C#/Razor?

I am 90% sure you can't do this without a hack. Even though they look like a standard HTML file, they are separate as a convenience. They are typically streamed into your JS code on build.
That said, my 10% answer is that you could probably do something that would wrap a server call in a JS nugget so you could keep the actual CHTML server-side. You should be able to bake a script section that calls out like this: ASP.NET MVC rendering partial view with jQuery ajax

Can you give your scenario of why you would want to do this?
Angular 2 (Javascript/Typescript) is client side (though it still uses a transpiler to convert TS to JS.
While cshtml files are compiled through the ASP.NET compiler as they are apart of the declarative resources in ASP.Net structure.
Razor syntax needs an engine that understands what the symbols means the compiler holds references to these so that when it's interpreted it generates the correct code under the hood. However they are dynamically compiled by the ASP.NET runtime.
See more info here: Why isn't a compilation needed when updating cshtml files with .net code?
https://weblogs.asp.net/scottgu/introducing-razor

Can you include C# in (angular 2) component files? The answer is no and why would you want to do that anyway? I use Angular2 and Asp.net MVC together all the time. But it's important, conceptually, to understand a few things:
Let asp.net handle the backend, and let Angular2 handle the front end.
Otherwise don't mix the two (unless you are into Angular Universal in which your ng2 app is pre-rendered on the server, but this is a special topic).
I separate these concerns so completely that, when I am developing, I use the angular-cli within the context of Visual Studio Code, i.e. not one byte of .net is present in the Angular2 development environment.
Now of course your ng2 app is probably going to want to make calls to "the server", i.e. make http calls etc such as the following:
getMeSomeServerData(someVar: string): Promise < IGenericRestResponse > {
let headers = new Headers();
headers.append("Content-Type", "application/json");
let url = this.apiUrl + "getMeSomeServerData";
let post = this.http.post(url, JSON.stringify(someVar), {
headers: headers
}).map(response => response.json());
return post.toPromise();
}
The key thing to notice here is:
this.apiUrl
When I am in development mode I make this refer to my back-end project located at something like http://localhost:1234/ which refers to an asp.net MVC project i am running concurrently in Visual Studio. So the back-end looks something like this:
[HttpPost()]
[Route("getMeSomeServerData")]
public JsonNetResult GetMeSomeServerData(string someVar) {
GenericRestResponse response = new GenericRestResponse();
response.Error = false;
// do somthing
return new JsonNetResult(response);
}
Note: you have to configure your asp.net mvc backend for CORS or cross-origin HTTP requests since your ng2 app is not on your mvc project domain.
Now, if you like, you CAN have your backend service return text, i.e HTML. Which means you can even go so far as to return partial cshtml views, which is just text after all. Then on the front end, your ng2 app can inject the html however you like. This generally defeats the purpose of Angular 2, in my opinion, and your server can become bogged down with rendering views. But it's up to you.
In any case, when you want to deploy your app for production, then you use the the angular-cli command to bundle and optimize your ng2 app ("ng build -prod"). Then copy all the assets in the "prod" folder to your asp.net mvc project (gulp makes this fast and easy). Use ONE razor view and one razor view only to server your webpage. Here is an example of such a view, Home.cshtml:
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script type="text/javascript" src="~/assets/js/styles.bundle.min.js"></script>
</head>
<body>
<app>Loading...</app>
<script type="text/javascript" src="~/assets/js/main.bundle.min.js"></script>
</body>
</html>
And THATS ALL you use razor views for: to serve your initial SPA page view. Just don't forget to change your "apiUrl" in your app to reflect the http calls are going locally.

You can create an Asp.Net MVC application and then add the Angular Libraries and setup your App to use the default Layout and default controller Index action.
Then you can create partial actions and use its URL as a template for the Angular route, ex:
templateUrl: 'YourController/YourPartialAction'
Although this will work, but I don't think it is recommended cause you mixed both MVC and Angular, Angular is supposed to be totally client side and separated from your back end

Related

Should I be mixing .cshtml files and .razor files in my .NET 6 project?

I'm not trying to specifically create a Blazor Web application, rather I'm rewriting an old ASP.Net Framework application in Razor and the newest .NET (currently .NET 6). I've created a .razor component for my Footer that is going to appear in all of my pages. I'm unable to get it to display, I currently have this:
#section Footer {
<component type="typeof(NewProject.Pages.Footer)" render-mode="Static"/>
}
But then I have read that .razor files are supposed to be used in Blazor Web applications and they should be used instead of .cshtml files. I'm trying to stick to Razor pages and MVVM instead of MVC, and I'm still very new to both Razor and Blazor, and before I get too much further into this, I would like to know if I should instead create the Footer as a Partial View instead of a Blazor component. These are the files I've created.
Microsoft's answer, apparently, is a big yes. The default Blazor project uses cshtml as the foundation for the site, as well as for the scaffolded Identity system, and razor for everything else.
I know you're not planning to use Blazor, but the above indicates to me that they're meant to co-exist.

Render html files from ASP.NET Razor cshtml files

I have a web app built with ASP.NET 4.6.1 and uses the Razor view engine. Is it possible to execute a command that will render all my template files (.cshtml files) to static HTML?
I need static HTML files for certain steps in my build process and I can't think of how to render all my view files into html.
I was thinking of something like what you are talking about, but my idea was a way to generate JS files (for building PhoneGap apps, for instance). The project was on BitBucket. The controller/view can generate the JS files necessary for executing the app, which was done by going to a URL to render the content, which you can view in the demo app. Any controller in the app marked with a special attribute gets rendered out to a target folder.
I was hoping to invest more into it but didn't get too far. However this was pretty easy to setup so I hope it can give you a starting point. At worse, you can create a process that spawns a browser to target this URL... At best, there is probably a better way to internalize the components to run "out of band."
Not sure if exist a easy solution for that. But if you really need it through the build process I suggest to create a consoleApp and call it from the build.For the console you can use the RazorEngine it compile/parse the razor for you.

Simplified "Razor-Only" website?

I have a website I want to make using the Razor template engine, however it really only has one simple page with a basic AJAX form in it. Having a full-blown MVC Web Application seems like a massive overkill for this, but I don't want to have to use something like PHP. Can I use Razor in a 'PHP-like' manner (i.e. one or two .cshtml/.vbhtml pages I can make requests to, in a similar function to how you make requests to .php pages)?
This will be hosted on IIS 8, if that'll help.
You can use razor with ASP.NET Websites (not web projects).
To do this go to File > New Web Site... and pick one of the templates that supports razor.
http://msdn.microsoft.com/en-us/library/gg606533%28v=vs.100%29.aspx
Gives more depth, however, you might be able to skip the first step "Installing the ASP.NET Razor Tools" if you already have it installed.

How to use ASP.NET to render HTML pages from within another assembly?

I am running the executable application (a WinForms one) and I have faced the need to render several HTML pages (kind of "active" - it consumes the model and produces the HTML code of the whole page).
I am looking to the referencing the MVC or ASP.NET project. What is the best way to use these (or maybe other tools; if so, they what are they?) projects to render raw HTML code from the model and some sort of View Page?
See the following SO question about hosting ASP.Net in WinForms projects - its entirely doable!
Hosting ASP.NET within my application
In reply to AgentFires comment about doing it without a http host involved (which Im assuming he means a web server), try these two articles from Rick Strahl about hosting the ASP.Net runtime directly.
http://www.west-wind.com/presentations/aspnetruntime/aspnetruntime.asp
http://www.west-wind.com/weblog/posts/2005/Jul/20/AspNET-Runtime-Hosting-Update
They are fairly old, but they should get you started.
If your are getting a html string back, then you can injec that html code into the browser control

Localizing JavaScript strings in an ASP.NET Web Forms application

One of the apps I work on is a large ASP.NET 3.5 Web Forms app that is used in the U.S., Central and South Americas, and Europe. We're also starting to do more work with AJAX, and thus we need to settle on a strategy for localizing strings in our JavaScript controls.
For example, we have a control written as a jQuery plugin that formats data into a sortable table. The buttons and table columns need to be localizable.
We're currently using two different approaches to handle this scenario, but I'm not completely satisfied with either.
Write the bulk of the code in a jQuery plugin style, then place a script block on the .aspx page where we'll pull in values from a .resx file and feed them into the plugin code. Here's an example in pseudo code:
<script>
var view;
$(function() {
view = {
columnHeaders: {
productNumber = <%$ Resources:WidgetProductNumber_HeaderText %>,
productDescription = <%$ Resources:WidgetProductDescription_HeaderText %>
}
};
});
</script>
Place the JavaScript in plain .js files with custom tokens in place of strings. We have a handrolled HttpModule that will parse JavaScript files and replace the tokens with values from any existing .resx file whose file name matches the name of the JavaScript file being processed.
Both approaches have problems. I'd prefer to keep our JavaScript code separate from our .aspx pages to make it more unobtrusive and reusable.
The HttpModule approach is clever but a little opaque to developers. I'm also looking to implement a JavaScript bundler called Rejuicer, which is also written as an HttpModule, and getting these to work together seems like it would require customizing the open source code. I'd prefer to use the code as it's written so that we can upgrade it as the project progresses.
Are there any other tried-and-true strategies for approaching this problem in ASP.NET?
It seems that both approaches are a little more complex/cumbersome than necessary. Keep it simple.
1) Using an .ashx, custom http handler, or web service, create a .net object (anonymous, custom -- doesn't matter) that matches the client side JSON object.
2) Populate server side object's properties with the localized values
3) Set the response content type to text/json or text/javascript.
4) Using the JavaScriptSerializer class, serialize the object into the response stream.
From the client side, you have two options:
1) Use an AJAX call to the .ashx/handler/service to set your client side "view" object to the response JSON.
2) Create a script tag with the src="the/path/to/the/serviceOrHandler". In this case you would need to include the js variable declaration in your response output.
Let me know if you need a code sample.
I just stumbled onto this question, and I have another answer to throw into the ring. It isn't my work or anything, but it looks like a fairly elegant solution. It involves writing a localization handler to serve up ASP.NET resources to Javascript. Here are a couple of links:
http://weblog.west-wind.com/posts/2009/Apr/02/A-Localization-Handler-to-serve-ASPNET-Resources-to-JavaScript
http://www.tikalk.com/use-aspnet-resource-strings-within-javascript-files/

Categories