3

I just started programming at MVC and I would like to ask about the best way to call a controller's method from your view. To make it easier: I have a model called Song with 2 methods to start and stop it:

public class Song
{
        WMPLib.WindowsMediaPlayer wplayer ;

        public Song() {
            wplayer = new WMPLib.WindowsMediaPlayer();
            wplayer.URL = "my song url";
            wplayer.controls.stop();
        }
        public void Stop() {
            wplayer.controls.stop();
        }
        public void Start() {
            wplayer.controls.play();
        }
    }

In the controller I create the song object and I have two functions to start and stop it.

public class DefaultController : Controller
        {
            // GET: Default
            Song c = new Song();

            public ActionResult Index()
            {
                return View(c);
            }
            public void Start() {
                c.Start();            
            }
            public void Stop() {
                c.Stop();
            }
        }

In the view I have 2 buttons that correspond to each controller action.

<button type="button">Start</button>
<button type="button">Stop</button>

How can I do the most correct way to call each controller action from the view buttons?

Thank you very much for your attention, I appreciate your help

Monish Koyott
  • 374
  • 1
  • 4
  • 20
F. Iván
  • 167
  • 1
  • 1
  • 12
  • 1
    `Start()` and `Stop()` would be controller actions which you call with AJAX. Also remember each request creates a new controller instance so that Song instance is also lost after the action has executed. – Jasen Dec 29 '17 at 03:06

2 Answers2

10

You can use set href path to call your controller from view.

<a class="btn btn-success" href="@Url.Action("Start", "DefaultController")">Start</a>

and if want to pass parameter then:

<a class="btn btn-success" href="@Url.Action("Start","DefaultController", new {id=Item.id })">Start</a>

or for other options you can check this link

you can call your controller method using ajax also refer this link

Saurabh Solanki
  • 2,146
  • 18
  • 31
2

A very simple way to achieve this is by using Razor as shown below:

<button type="button" onclick="location.href='@Url.Action("Start", "DefaultController")'">Start</button> 

  <button type="button" onclick="location.href='@Url.Action("Stop", "DefaultController")'">Stop</button>
Frank Odoom
  • 1,545
  • 18
  • 19