Auto inject javascript in blazor application - c#

I'm developing a Blazor extension library.
One thing in this library would be the reuse of the javascript alert() method.
I know how to do this, this involves adding this in a .cshtml page:
<script>
Blazor.registerFunction('Alert', (message) => {
alert(message);
});
</script>
and this in my code:
public void Alert(string message)
{
RegisteredFunction.Invoke<object>("Alert", message);
}
I would like the javascript part somehow to be auto injected in the html if you use my package (or maybe always). Not sure if this is possible (yet)
Any ideas on this?

Edit
Since blazor 0.2 there is a more supported way to do this. Look at the blazorlib template for an example:
dotnet new -i Microsoft.AspNetCore.Blazor.Templates
dotnet new blazorlib
0.1 answer
I ended up with creating my own blazor component containing my javascript, like this:
public class BlazorExtensionScripts : Microsoft.AspNetCore.Blazor.Components.BlazorComponent
{
protected override void BuildRenderTree(Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder builder)
{
builder.OpenElement(0, "script");
builder.AddContent(1, "Blazor.registerFunction('Alert', (message) => { alert(message); });");
builder.CloseElement();
}
}
And adding it to my app.cshtml like this:
#addTagHelper *, BlazorExtensions
<Router AppAssembly=typeof(Program).Assembly />
<BlazorExtensionScripts></BlazorExtensionScripts>

Related

Using React form submission in C# .NET Controller class

I'm learning how to use React with .NET and am using the Visual Studio templates provided to play around (I'm using a Mac, if that is useful for context). I am starting with very simple back end applications and trying to get my React front end to link to these. I am very new to using React and .NET so I apologise if the questions I ask seem simple. Here is my current issue:
I have the following C# Controller class which retrieves and returns the middle letters of a string:
MiddleLetterController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace TestingReactDotNet.Controllers
{
public class MiddleLetterController : Controller
{
public string GetMiddle(string word)
{
if (word.Length % 2 == 0)
{
return word.Substring(word.Length / 2 - 1, 2);
}
else
{
return word.Substring(word.Length / 2, 1);
}
}
}
}
I am using React on the front end and want whatever the user types and submits in the form to be the word passed as an argument to the GetMiddle() method and for this to be displayed on screen.
My current MiddleLetter.js file is:
import React, { Component } from "react";
export class MiddleLetter extends Component {
state = {
word: "",
};
updateInput(key, value) {
// update react state
this.setState({
[key]: value
});
}
render() {
return (
<center>
<div className="App">
<div>
Type a word...
<br />
<input
type="text"
placeholder="Type word here ..."
value={this.state.word}
onChange={e => this.updateInput("word", e.target.value)}
/>
<button onClick={() => ?????)}>Submit</button>
<br />
</div>
</div>
</center>
);
}
}
I have looked at the React documentation but cannot work out how / the best way to link the React form submission to the backend application. I would be really grateful if anyone had any suggestions please :) Thank you.
You're probably going to want to pull in a library like axios or fetch into your react project "yarn add axios" in your react folder.
Then at the top of your MiddleLetter.js you'll need to import axios from axios;
create an instance of axios in MiddleLetter.js, something like:
const instance = axios.create({
baseURL: "localhost:{whatever port you're running on}",
)}
Then in your "updateInput" function where your comments are add:
const response = await instance.get("/middleletter/" + value);
your response should have the return value from the controller.
Then for your controller.
add [HttpGet({word})]
over public string GetMiddle(string word)
This will let the controller get the word from your URL.
There are better ways to do all of this. But this should get you where you need to go.

Ajax.Pro.dll in .NET 4.5

Now, I upgrade my web application from .NET4.0 to 4.5.2.
In my app, I use Ajax.Pro.dll.
In aspx.file, call ajaxMethod like follow by javascript.
function callAjax() {
ajaxClass.ajaxMethod();
}
In cs.file there are ajaxMethod like follow.
class AjaxClass
{
[AjaxPro.AjaxMethod]
public void AjaxMethod()
{
this.textBox.text = "AjaxCalled!!";
}
}
In .NET4.0, My app ran completely. But in .NET4.5, ajaxClass is null.
Is Ajax.Pro.dll used in .NET4.5?
Please answer my problem.

How to use HtmlTextWritter in MVC6

I am a beginner in mvc. When I upgrade my project into MVC6, I have face some problems and also unable to find the solution. My code block is :
public static void WriteTo(HtmlHelper helper, string value)
{
var baseWriter = helper.ViewContext.Writer;
using (HtmlTextWriter textWriter = new HtmlTextWriter(baseWriter))
{
textWriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
textWriter.RenderBeginTag(HtmlTextWriterTag.Script);
textWriter.Write(value);
textWriter.RenderEndTag();
}
}
If there is any way to achieve the same scenario(like use of the HtmlTextWritter) in MVC6 or if there is any mistake in my code block.can you please suggest the solution. Even tried with google, but I can't get the opt solution.
The MVC equivalent of that archaic format (HtmlTextWriter is for WebForms) is this:
<script type="text/javascript">#value</script>
Where value is a variable that is present in your view.

XSockets - custom controller is not registering

I've been trying to evaluate XSockets but it appears I've hit my first stumbling block pretty early. I can connect to Generic controller just fine but custom controllers do not seem to work at all - I get a custom message: "The handler name was not found in loaded plugins". A Google search shows one other person having this problem in SE, but their solution did not work for me.
I've created a console project and installed the latest XSockets 3.03 from NuGet. My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSockets.Core.Common.Socket;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
using XSockets.Core.Common.Socket.Event.Interface;
namespace XSockets2
{
class Program
{
static void Main(string[] args)
{
using (var server = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>())
{
Console.WriteLine("running!");
server.StartServers();
Console.ReadLine();
server.StopServers();
}
}
}
public class TestCont: XSocketController
{
public override void OnMessage(ITextArgs textArgs)
{
this.SendToAll(textArgs);
}
}
}
And my Javascript
function connect2() {
var host = "ws://localhost:4502/testcont";
var conn;
conn = new XSockets.WebSocket(host);
conn.on(XSockets.Events.open, function (clientInfo) {
message(clientInfo.ClientGuid); //appends message to textarea
console.log('Open', clientInfo);
});
conn.on('OnMessage', function (d) {
message(d);
console.log('Message', d);
});
conn.on(XSockets.Events.onError, function (err) {
message(err.CustomMessage);
console.log('Error', err);
});
conn.on(XSockets.Events.close, function () {
message('Closed');
console.log('Closed');
});
First of all the latest version is 3.0.2 (not 3.0.3) but that is not important :)
There is a well known and documented bug in the plugin framework for the latest version. The bug only affect you if you run a console application (or any other *.exe) project since xsockets by default only looks in *.dll and not *.exe.
The issue and work around is described here
But your code will not work anyway since you have an error (from what I can see).
Your controller is named "TestCont" but you connect to "testcont". The connectionstring is case sensitive.
EDIT: I also think you are missunderstanding the method OnMessage since you have added a subscription to that exact name.

Nancy Self Host doesn't call Module?

I am working on adding Nancy Framework to my C# console application (followed the very short tutorial here and it loads a blank page when I go to http://localhost:1234 so I know it is starting, but it doesn't show my text properly. I have gone over my code various times, but don't see any issues.
I have added both Nancy and Nancy.Hosting.Self to my project.
static void Main(string[] args)
{
var nancyHost = new Nancy.Hosting.Self.NancyHost(new Uri("http://localhost:1234"));
nancyHost.Start();
Console.ReadLine();
nancyHost.Stop();
}
namespace DaemonApp
{
class MainModule : Nancy.NancyModule
{
public MainModule()
{
Get["/"] = parameters =>
{
return "Hello world!";
};
}
}
}
I added some print lines, and it never calls the module when I visit the page. Does anyone have any clue what the issue is?
I didn't make the Module class public, that fixed it instantly =/

Categories

Resources