从.Net(MVC)中的视图按钮调用控制器方法的最简单方法 [英] Simplest way to call a controller method from a view button in .Net (mvc)

查看:750
本文介绍了从.Net(MVC)中的视图按钮调用控制器方法的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在MVC编程,我想从您的角度询问调用控制器方法的最佳方法. 为了使它更容易: 我有一个名为Song的模型,其中有2种方法可以启动和停止它:

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();
            }
        }

在视图中,我有2个按钮,分别与每个控制器操作相对应.

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

推荐答案

您可以使用set href路径从view调用controller.

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

您可以使用ajax调用控制器方法,也请参考

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

这篇关于从.Net(MVC)中的视图按钮调用控制器方法的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆