如何获取{ID}在网址"控制器/操作/ ID"在后行动? [英] How to get {ID} in url "controller/action/id" in a post action?

查看:116
本文介绍了如何获取{ID}在网址"控制器/操作/ ID"在后行动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CSHTML文件,我在下面的JavaScript主页/细节/ 4 。图4是标识

In the cshtml file, I have the following javascript in Home/Details/4. 4 is the ID.

<script>
    $(document).ready(function () {
        $("#checkbox").click(function () {
            $.post(
                "Home/Toggle", 
                { checkbox: $("#checkbox").val() }, 
                function (data) {

            });
        });
    });
</script>

以下是在控制器的动作code

The following is the action code in the controller.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Toggle(bool checkbox)
    {
        ...... // How to get ID?
        var x = db.XXXX.Find(id);

如何获得ID?从一些路由数据,或URL,或者让前jQuery的帖子传递?

How to get the ID? From some routing data, or Url, or let the front jQuery posting pass it?

是否有可能获得操作方法的ID,而无需从前面的HTML页面传递?

推荐答案

首先削减缺少在url控制器名称前:

First of all slash before the controller name in the url is missing:

"/Home/Toggle"

接下来的错误是复选框值不能使用VAL()方法来检查,但它可以检查使用:

Next mistake is checkbox value can not be check by using val() method but it can be checked using:

$("#checkbox").is(':checked')

接下来,您必须为它映射像在URL后追加ID控制器/动作/(编号)中的RegisterRoutes方法RouteConfig.cs文件。

Next you have to append id after the url as it mapped like "controller/action/{id}" in RouteConfig.cs file in RegisterRoutes method.

因此​​,最终的正确网址是:

So your final correct url will be:

"/Home/Toggle/{id}"  //in your case: "/Home/Toggle/4"

在行动方法ID参数也不翼而飞。纠正动作的方法是:

In Action method "id" parameter is also missing. Corrected Action method is:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public void Toggle(bool checkbox, int id)
    {

    }

和您的完整和纠正Jquery的code是:

And your complete and corrected Jquery code is:

$.post("/Home/Toggle/4", { checkbox: $("#checkbox").is(':checked') }, function (data) {

            });

这篇关于如何获取{ID}在网址&QUOT;控制器/操作/ ID&QUOT;在后行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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