Boris
Boris

Reputation: 57

method is called twice

What was I doing wrong? My method is called twice. First time I get Id and it's correct behavior Second time I get Null I can't get it what is correct way to solve it?

My View

 <div class="container">
    <div class="row">
        @foreach (var item in Model)
        {
            <div class="col-md-4">
                <div class="card" style="width: 18rem;">
                    <img src="~/Content/not-found-image.jpg" class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">@item.Name</h5>
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                        <div id="textButton">
                            <a class="btn btn-primary" data-index="@item.Id" name="link">Go to anywhere</a>
                        </div>
                    </div>
                </div>
            </div>
        }
    </div>
</div>

My Controller

[HttpGet]
public ActionResult ListCoach(int id)
{    
    if (id != null)
    {
        var ChoachList = _TraningService.Coach(id);
        return View(ChoachList);
    }

    return HttpNotFound();

}

Script I use script on My View use helper @Section {}

@section scripts {
    @*<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>*@
    <script>
        function PassToContoller(data) {
            //alert(data);
            $.ajax({
                type: "GET",
                url: '/TrainingType/ListCoach',
                data: { id: data },
                success: function (data) {
                    console.log(data);
                    window.location.href = '/TrainingType/ListCoach';
                    return data;
                },
                error: function () {
                    $("#loader").fadeOut("slow");
                    console.log("error1");
                }
            });
        }
        $(document).ready(function () {
            $("a[name=link]").on("click", function () {
                var valueOfClickedTag = $(this).data("index");
                alert("Clicked: " + valueOfClickedTag);
                var callFunc = PassToContoller(valueOfClickedTag)
            });

            $(":button[id=GoToAnywhere3]").on("click", function () {
                var valueOfClickedBtn = $(this).data("index");
                var callFunc = PassToContoller(valueOfClickedBtn)
            });
        });
    </script>
}

if I use the method: I can't get into View ListCoach Can I return Json on My View?

[HttpGet]
    public JsonResult ListCoach(int id)
    {
        var ChoachList = _TraningService.Coach(id);

        return Json(ChoachList,JsonRequestBehavior.AllowGet);
    }

Upvotes: 2

Views: 2144

Answers (2)

Yiyi You
Yiyi You

Reputation: 18159

In your function PassToContoller,in ajax success,you use window.location.href = '/TrainingType/ListCoach';,so after you call the function,it will have two requests,one with ajax,one with window.location.href.

If you want to get jsondata in ajax,you need to use dataType: "json", in ajax. Here is a demo to pass json data:

Action:

[HttpGet]
        public JsonResult GetJson(int id)
        {
            return new JsonResult(new TestModel { Id=id,Name="Test"});
        }

View:

<button onclick="test()">
    test
</button>
@section scripts
{
    <script>
        function test() {
           $.ajax({
                type: "GET",
                url: 'GetJson',
                data: { id: 1 },
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    
                },
                error: function () {
                    $("#loader").fadeOut("slow");
                    console.log("error1");
                }
            });
        }
    </script>
}

result: enter image description here

Update:

You can try to use a form to pass Id to action(without using <a></a>):

<form asp-action="GetJson" asp-route-id="@item.Id">
    <input type="submit" value="Go to anywhere" />
</form>

Action:

[HttpGet]
        public IActionResult GetJson(int id)
        {
            return View("Index",new List<TestModel> { new TestModel { Id = id, Name = "Test" } });
        }

Upvotes: 1

mfarahy
mfarahy

Reputation: 88

Your code seems to be OK and in theory, your action should not call twice but I want to show you some ways in order to catch the problem:

  1. when a call is made to the server in chrome developer tools in the tab network you will see a record in which there is a column named Initiator that shows you the call is created by who and where.
  2. you can use keyword DEBUG in the first of function PassToContoller and look at the stack to know who one call your function

and about your final question, my answer is negative and you can not use this way to pass JSON object to your view but you can pass JSON object beside model by ViewBag or ViewData

Upvotes: 1

Related Questions