0

I am using ASP.NET Razor Template to create a web app, that i can use to start and stop services through. I have a text box,in which i can feed in service and a Start and Stop button

<div>

        <form>
            Service Name:<br>
            <input type="text" name="servicename"><br>
            <button onclick=@Model.StartService("servicename")>Start</button>   <button onclick=@Model.StopService("servicename")>Start</button>
        </form>
</div>

I have a Model that has the stop and Start service Method that takes in the service name as the argument. Running my app automaically calls the StartService and StopService. I want them to be invoked only when the button is clicked

Here is my model

public  string StopService(string serviceName)
{
    ServiceController[] controller = ServiceController.GetServices(serviceName);
    if (controller == null)
    {
        return null;
    }

    controller[0].Stop();
    controller[0].WaitForStatus(ServiceControllerStatus.Stopped);
    return controller[0].Status.ToString();
}

public  string StartService(string serviceName)
{
    ServiceController[] controller = ServiceController.GetServices(serviceName);
    if (controller == null)
    {
        return null ;
    }

    controller[0].Start();
    controller[0].WaitForStatus(ServiceControllerStatus.Running);
    return controller[0].Status.ToString();
}

I could be doing it all wrong but i am very new to this. I want to achieve this through the suggested the web template (ie., using Razor Page)

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
alangilbi
  • 321
  • 5
  • 17

1 Answers1

0

You're missing the concept of client-server here. Your StartService and StopService methods exist server-side, but onclick only means anything client-side, and specifically the actual click by the user that would activate it happens client-side. You cannot directly call some server-side method like you're attempting to do client-side. In fact, all that's happening here is that Razor is actually running your StartService and StopService methods during rendering of the view in order to try to fill the onclick attributes with the return values. So the end result is that your HTML will look like onclick="Started", where "Started" is perhaps one of your Status values.

Long and short, if you need to activate something on the server when a use clicks a button, you must submit a request to the server. That can be done via a traditional form post (which will cause the page to refresh) or via AJAX. In either case, you would post to a route with a handler that would then start/stop your service.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444