Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

asp.net - How to get {ID} in url "controller/action/id" in a post action?

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>

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

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

Is it possible to get the ID from the action method without passing from the front html page?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

"/Home/Toggle"

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

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

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"

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

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

    }

And your complete and corrected Jquery code is:

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

            });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...