I have an ASP.NET Core MVC application with a couple of coded in functions in the .cshtml pages(Razor). This one in particular I'd like to run when an a-tag gets clicked on. This code will essential will go to a locally stored .svg file and change some of the styling attributes. The code for that is below, and is stored in the View.
public static void turnRed()
{
var pathToSVG = "path/to/svg";
var doc = XDocument.Load(pathToSVG);
var node = doc.Descendants(XName.Get("rect", "http://www.w3.org/2000/svg")).FirstOrDefault(cd => cd.Attribute("id").Value == "rect1");
node.SetAttributeValue("fill", "red");
doc.Save(pathToSVG);
}
Now in the actual html I would like to have a simple onclick expression that would run the code when the a-tag gets pressed.
<a onclick="@{ turnRed(); }" href="#">Change SVG color</a>
What I have right now for whatever reason gets called onl oad, and not on click. How might I go about this? If there's a way to to do it without JavaScript, that would be ideal, but whatever works. Thanks!
Here are some of the concepts I've looked at and tried already:
Using Razor to call C# function
https://www.c-sharpcorner.com/blogs/how-to-create-razor-function-in-asp-net-mvc-view1
https://asp.mvc-tutorial.com/razor/local-functions/
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-6.0
CodePudding user response:
Razor page allows the use of handler methods
. To call a method from your page you need to put On
the http verb your method name. In my tests this didn't work with static methods
Change your signature method for:
public void OnGetTurnRed()
And change your 'a' for:
<a asp-page-handler="TurnRed">Change SVG color</a>