ASP Core 2.0 - 从视图调用控制器功能

时间:2018-04-21 13:55:08

标签: c# html web core

我是ASP Core和Web开发的完全初学者,所以如果这很明显,我会道歉。

我正在寻找一种从我的View中调用Controller中存在的函数的方法。响应用户点击其网页上的按钮,将调用此函数。

控制器功能:

public ActionResult Change(int n)
    {
        ViewData["currentChoice"] = choiceArray[n];
        return View();
    }

查看:

@{
    Choice currentPoint = ViewData["currentChoice"] as Choice;
    <h2>@currentPoint.text</h2>
}

//Button - Call Change function in the Controller 

我之前创建了一个链接到另一个页面的按钮,在这种情况下&#34;问题/更改&#34;,但我不想要重定向。所需的最终结果只是通过更改ViewData来更新屏幕上的文本。

2 个答案:

答案 0 :(得分:0)

在MVC控制器中,动作(函数)通过​​http请求调用,这些请求以锚元素,AJAX调用或表单提交的形式源自您的视图。

MVC有很好的助手为锚元素生成正确的URL,映射到您选择的操作。

@{
Choice currentPoint = ViewData["currentChoice"] as Choice;
<h2>@currentPoint.text</h2>
}
<a href="@Url.Action("YourController", "Change")">Change</a>

答案 1 :(得分:0)

尝试一下 因为您使用的是ASP.NET核心,所以您的锚标记应该像这样

<a asp-controller="YourControllerName" asp-action="Change" class="btn btn-primary" onClick="changeChoice()">Change</a>

添加JS

<script type="text/javascript">
    $('document').ready(function () 
    {
        function changeChoice() 
        {
            $.ajax(
                {
                    url: '/YourControllerName/Change
                    type: 'GET',
                    success: function (response) {
                        alert('Successfully Updated'),
                        location.reload()
                    },
                });
        }
    });
</script>