Asp razor in javascript

Use Razor components in JavaScript apps and SPA frameworks

This isn’t the latest version of this article. For the current release, see the .NET 7 version of this article.

This information relates to a pre-release product that may be substantially modified before it’s commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

For the current release, see the .NET 7 version of this article.

This article covers how to render Razor components from JavaScript, use Blazor custom elements, and generate Angular and React components.

Render Razor components from JavaScript

Razor components can be dynamically-rendered from JavaScript (JS) for existing JS apps.

The example in this section renders the following Razor component into a page via JS.

In Program.cs , add the namespace for the location of the component. The following example assumes that the Quote component is in the app’s Shared folder, and the app’s namespace is BlazorSample :

Call RegisterForJavaScript on the app’s root component collection to register the a Razor component as a root component for JS rendering.

RegisterForJavaScript includes an overload that accepts the name of a JS function that executes initialization logic ( javaScriptInitializer ). The JS function is called once per component registration immediately after the Blazor app starts and before any components are rendered. This function can be used for integration with JS technologies, such as HTML custom elements or a JS-based SPA framework.

One or more initializer functions can be created and called by different component registrations. The typical use case is to reuse the same initializer function for multiple components, which is expected if the initializer function is configuring integration with custom elements or another JS-based SPA framework.

Don’t confuse the javaScriptInitializer parameter of RegisterForJavaScript with JavaScript initializers. The name of the parameter and the JS initializers feature is coincidental.

The following example demonstrates the dynamic registration of the preceding Quote component with » quote » as the identifier.

    In a Blazor Server app, modify the call to AddServerSideBlazor in Program.cs :

builder.Services.AddServerSideBlazor(options => < options.RootComponents.RegisterForJavaScript(identifier: "quote", javaScriptInitializer: "initializeComponent"); >); 
builder.RootComponents.RegisterForJavaScript(identifier: "quote", javaScriptInitializer: "initializeComponent"); 

Attach the initializer function with name and parameters function parameters to the window object. For demonstration purposes, the following initializeComponent function logs the name and parameters of the registered component.

window.initializeComponent = (name, parameters) => < console.log(< name: name, parameters: parameters >); > 

Render the component from JS into a container element using the registered identifier, passing component parameters as needed.

  • The Quote component ( quote identifier) is rendered into the quoteContainer element when the showQuote function is called.
  • A quote string is passed to the component’s Text parameter.

Load Blazor ( blazor.server.js or blazor.webassembly.js ) with the preceding scripts into the JS app:

In HTML, place the target container element ( quoteContainer ). For the demonstration in this section, a button triggers rendering the Quote component by calling the showQuote JS function:

 On initialization before any components are rendered, the browser's developer tools console logs the Quote component's identifier ( name ) and parameters ( parameters ) when initializeComponent is called:
Object < name: "quote", parameters: (1) […] >name: "quote" parameters: Array [ ] 0: Object < name: "Text", type: "string" >length: 1 

When the Show Quote button is selected, the Quote component is rendered with the quote stored in Text displayed:

Quote rendered in the browser

rootComponents.add returns an instance of the component. Call dispose on the instance to release it:

const rootComponent = await window.Blazor.rootComponents.add(. ); . rootComponent.dispose(); 

The preceding example dynamically renders the root component when the showQuote() JS function is called. To render a root component into a container element when Blazor starts, use a JavaScript initializer to render the component, as the following example demonstrates.

The following example builds on the preceding example, using the Quote component, the root component registration in Program.cs , and the initialization of jsComponentInitializers.js . The showQuote() function (and the script.js file) aren’t used.

In HTML, place the target container element, quoteContainer2 for this example:

Using a JavaScript initializer, add the root component to the target container element.
export function afterStarted(blazor) < let targetElement = document.getElementById('quoteContainer2'); blazor.rootComponents.add(targetElement, 'quote', < text: "Crow: I have my doubts that this movie is actually 'starring' " + "anybody. More like, 'camera is generally pointed at.'" >); > 

For the call to rootComponents.add , use the blazor parameter (lowercase b ) provided by afterStarted . Although the registration is valid when using the Blazor object (uppercase B ), the preferred approach is to use the parameter.

For an advanced example with additional features, see the example in the BasicTestApp of the ASP.NET Core reference source ( dotnet/aspnetcore GitHub repository):

Documentation links to .NET reference source usually load the repository’s default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Blazor custom elements

Use Blazor custom elements to dynamically render Razor components from other SPA frameworks, such as Angular or React.

  • Use standard HTML interfaces to implement custom HTML elements.
  • Eliminate the need to manually manage the state and lifecycle of root Razor components using JavaScript APIs.
  • Are useful for gradually introducing Razor components into existing projects written in other SPA frameworks.

Element name

Per the HTML specification, custom element tag names must adopt kebab case:

❌ Invalid: mycounter
❌ Invalid: MY-COUNTER
❌ Invalid: MyCounter
✔️ Valid: my-counter
✔️ Valid: my-cool-counter

Package

Add a package reference for Microsoft.AspNetCore.Components.CustomElements to the app’s project file.

For guidance on adding packages to .NET apps, see the articles under Install and manage packages at Package consumption workflow (NuGet documentation). Confirm correct package versions at NuGet.org.

Blazor Server registration

To register a root component as a custom element in a Blazor Server app, modify the call to AddServerSideBlazor in Program.cs . The following example registers the Counter component with the custom HTML element my-counter :

builder.Services.AddServerSideBlazor(options => < options.RootComponents.RegisterCustomElement("my-counter"); >); 

The preceding code example requires a namespace for the app’s components (for example, using BlazorSample.Pages; ) in the Program.cs file.

Blazor WebAssembly registration

To register a root component as a custom element in a Blazor WebAssembly app, call RegisterCustomElement on RootComponents in Program.cs . The following example registers the Counter component with the custom HTML element my-counter :

builder.RootComponents.RegisterCustomElement("my-counter"); 

The preceding code example requires a namespace for the app’s components (for example, using BlazorSample.Pages; ) in the Program.cs file.

Use the registered custom element

Use the custom element with any web framework. For example, the preceding my-counter custom HTML element that renders the app’s Counter component is used in a React app with the following markup:

For a complete example of how to create custom elements with Blazor, see the CustomElementsComponent component in the reference source.

Documentation links to .NET reference source usually load the repository’s default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Pass parameters

Pass parameters to your Blazor component either as HTML attributes or as JavaScript properties on the DOM element.

The following Counter component uses an IncrementAmount parameter to set the increment amount of the Click me button.

@page "/counter" 

Counter

Current count: @currentCount

@code < private int currentCount = 0; [Parameter] public int IncrementAmount < get; set; >= 1; private void IncrementCount() < currentCount += IncrementAmount; >>

Render the Counter component with the custom element and pass a value to the IncrementAmount parameter as an HTML attribute. The attribute name adopts kebab-case syntax ( increment-amount , not IncrementAmount ):

Alternatively, you can set the parameter’s value as a JavaScript property on the element object. The property name adopts camel case syntax ( incrementAmount , not IncrementAmount ):

const elem = document.querySelector("my-counter"); elem.incrementAmount = 10; 

You can update parameter values at any time using either attribute or property syntax.

Supported parameter types:

  • Using JavaScript property syntax, you can pass objects of any JSON-serializable type.
  • Using HTML attributes, you are limited to passing objects of string, boolean, or numerical types.

Experimental support is available for building custom elements using the Microsoft.AspNetCore.Components.CustomElements NuGet package. Custom elements use standard HTML interfaces to implement custom HTML elements.

Experimental features are provided for the purpose of exploring feature viability and may not ship in a stable version.

Register a root component as a custom element:

    In a Blazor Server app, modify the call to AddServerSideBlazor in Program.cs :

builder.Services.AddServerSideBlazor(options => < options.RootComponents.RegisterAsCustomElement("my-counter"); >); 

Note The preceding code example requires a namespace for the app’s components (for example, using BlazorSample.Pages; ) in the Program.cs file.

builder.RootComponents.RegisterAsCustomElement("my-counter"); 

Note The preceding code example requires a namespace for the app’s components (for example, using BlazorSample.Pages; ) in the Program.cs file.

Include the following tag in the app’s HTML before the Blazor script tag:

Use the custom element with any web framework. For example, the preceding counter custom element is used in a React app with the following markup:

The custom elements feature is currently experimental, unsupported, and subject to change or be removed at any time. We welcome your feedback on how well this particular approach meets your requirements.

Generate Angular and React components

Generate framework-specific JavaScript (JS) components from Razor components for web frameworks, such as Angular or React. This capability isn’t included with .NET, but is enabled by the support for rendering Razor components from JS. The JS component generation sample on GitHub demonstrates how to generate Angular and React components from Razor components. See the GitHub sample app’s README.md file for additional information.

The Angular and React component features are currently experimental, unsupported, and subject to change or be removed at any time. We welcome your feedback on how well this particular approach meets your requirements.

Feedback

Submit and view feedback for

Источник

access model in javascript asp .net mvc razor

model is undefined, as far as JavaScript is concerned. The server-side code in your view executes, well, server-side. JavaScript has no notion of that. It’s only concerned with the client-side output of that code. You can kind of mix the two, but need to keep in mind that the server-side components are just there to emit strings which will be part of the client-side output.

So, for example, if you have a property on your model called:

Then you can’t use it directly in JavaScript like this:

alert(Model.SomeProperty) // or alert(SomeProperty) 

That’s not using the razor view syntax to tell the view engine that there’s server-side code here. This is syntactically client-side code, and there is no Model client-side. So you need to indicate that there’s server-side pre-processing to do:

Additionally, if SomeProperty is a string, then keep in mind that it’s output isn’t going to include quotes. So you’d need to provide those for client-side code as well:

Thus, the server-side value of SomeProperty will be emitted here when it’s rendered to the client. So if the value is something like «Hello World» then the resulting client-side code would be:

The main thing is to keep in mind the separation between the server-side code and the client-side code. All JavaScript/HTML/CSS is just one big string as far as server-side code is concerned. The view is essentially just creating a big string to send to the browser. Once it’s in the browser, the client-side rendering knows the difference between JavaScript/HTML/CSS and executes accordingly, long after the server-side code is gone.

Источник

Читайте также:  Массив чисел фибоначчи питон
Оцените статью