Reputation: 167
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
Upvotes: 3
Views: 19343
Reputation: 2204
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
Upvotes: 10
Reputation: 1566
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>
Upvotes: 2