locked
Ajax Jquery RRS feed

  • Question

  • User-1422983141 posted

    I have some Jquery on my view to take the user selected ID from a list which is placed in a variable.

    My testing shows that the Jquery is called, takes the value from the variable, and then calls to the correct Controller and Action Result

    but the select ID is never past to the argument in the Action Result and the 3rd alert is never triggered.

    I do have an error:

    jquery-3.3.1.js:9600 GET http://localhost:56004/Home/GroupID?selectedId%3D=1 500 (Internal Server Error)

    @section Scripts
        <script>
            $(function () {
                $('div#Categories a').click(function () {
                    //e.preventDefault();
                    alert($(this).attr('id'));
                    selectedId = $(this).attr('id');
                    alert(selectedId);
    
                    $.ajax({
                        url: "GroupID",
                        data: {'selectedId=':selectedId},
                        type: "GET",
                        success: function (data) {
                            alert(data);    
                            $(selectedId).html(response)
                        }
                    });
                });
            });
        </script>
    End Section

    I don't know if I am close to writing the code correctly, and the Jquery has some convoluted code for testing, any help would be great, thank you

    P.S: I would like to update another list on the same view, from the users selection without reloading the whole page and possible make change to the code to update the Jquery from the list and remove the variable, but I'm not sure.  

    Friday, February 1, 2019 7:26 PM

Answers

  • User1520731567 posted

    Hi kvic,

    Actually,I'm not quite understand your code,because your ajax:

    $(function () {
                $('div#Categories a').click(function () {
                    selectedId = $(this).attr('id');
                    alert(selectedId);
    
                    $.ajax({
                        url: "_Materials",
                        data: { id: selectedId },
                        type: "POST",
                        success: function () {
                            alert("success");
                        }
                    });
    
                });
            });

    and 

    @Html.Partial("_Materials")

    And lack some other code.

    If you would like to find the solution to the problem,please post your complete code,so that I can reproduce your issue,such as: two views and two views' action...

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 7, 2019 2:35 AM

All replies

  • User475983607 posted

    Remove the "="

    data: {'selectedId=':selectedId},
    data: {'selectedId':selectedId},

    Friday, February 1, 2019 9:52 PM
  • User-1422983141 posted

    I did find that mistake and found that the data was returned.

    I have added to the code and get the alert("Fail")

     <script>
            $(function () {
                $('div#Categories a').click(function () {
                    //e.preventDefault();
                    alert($(this).attr('id'));
                    selectedId = $(this).attr('id');
                    alert(selectedId);
    
                    $.ajax({
                        url: "GroupID",
                        data: {id: selectedId},
                        type: "GET",
                        success: function (data) {
                            alert(data);    
                            //$(selectedId).html(response)
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert("Fail")
                        }
                    });
                });
            });
        </script>

    The error seems to be at the success: function (data) {

    I assume the data is being passed in if success but I dont get the alert.

     success: function (data) {
                            alert(data); 

    Friday, February 1, 2019 10:01 PM
  • User-2054057000 posted

    Change the error callback to :

    error: function (xhr, status, error) {  
        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
      

    You can also check this tutorial on MVC + jQuery AJAX - Calling A C# Function With jQuery AJAX In ASP.NET MVC

    Saturday, February 2, 2019 12:50 PM
  • User-1038772411 posted
    • Please First Make Async = False, BTW overall please make your ajax call like below pattern. i hope its work fine for you.

    Ajax Call


    type: "POST",
    url: '@Url.Action("ActionName", "ControllerName")',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: '{selectedId: "' + selectedId + '" }',
    async: false,

    * In Mvc Controller Method paramter name same to the ajax call name like :

    [HttpPost]
    Public ActionResult ActionName(string selectedId)
    {
    retun View();
    }

    # At the end from my understanding as per your question above solution definitely work for you. Thanks 

    Monday, February 4, 2019 5:41 AM
  • User1520731567 posted

    Hi kvic,

    You could add some breakpoints on your controller to check your code step by step at the back end.

    And open F12 developer tool,add breakpoints on javascript to check at front end.

    I think there are something wrong with your action in controller,maybe url is wrong,or the return is wrong,or else...

    You could judge by error messages in error function,

    if you still have problems,please post your action code.

    Best Regards.

    Yuki Tao

    Monday, February 4, 2019 7:16 AM
  • User-1422983141 posted

    Finally today I found the time to, as you said, add some break points and find the problems.

    I used this code to get the data I wanted from the home controller - _materials, which is a partial view in the same directory, Action Result.

    @section Scripts
        <script>
            $(function () {
                $('div#Categories a').click(function () {
                    selectedId = $(this).attr('id');
                    alert(selectedId);
    
                    $.ajax({
                        url: "_Materials",
                        data: { id: selectedId },
                        type: "POST",
                        success: function () {
                            alert("success");
                        }
                    });
    
                });
            });
        </script>
    End Section

    Everything runs and the partial view is pasted the data I expect

    @If Not ViewData("Group") Is Nothing Then
    
        @For Each i In ViewData("Group")
            @<div Class="form-check form-check-inline">
                <input Class="form-check-input" type="checkbox" id=">@i.GroupName" value="@i.GroupName" />
                <Label Class="form-check-label" for="item.GroupName">@i.GroupName</Label>
            </div>  
        Next
    Else
        @<input Class="form-check-input" type="checkbox" id="" value="" />
        @<Label Class="form-check-label" for="item.GroupName">Test</Label>
    End If

    if ViewData("Group") Is Nothing then I get the else and I see the checkbox on the index view.

    But  when ViewData("Group") loops through and creates all the expected data I don't see that on my index page 

    <div Class="col-md-8">
        @Html.Partial("_Materials")
    </div>

    I haven't a clue, but this for an other day unless you have any ideas, thanks

    Monday, February 4, 2019 10:16 AM
  • User1520731567 posted

    Hi kvic,

    if ViewData("Group") Is Nothing then I get the else and I see the checkbox on the index view.

    But  when ViewData("Group") loops through and creates all the expected data I don't see that on my index page 

    Please open F12 developer tool =>Console,to check if there is an error message.

    @For Each i In ViewData("Group")
            @<div Class="form-check form-check-inline">
                <input Class="form-check-input" type="checkbox" id=">@i.GroupName" value="@i.GroupName" />
                <Label Class="form-check-label" for="item.GroupName">@i.GroupName</Label>
            </div>  
        Next

    if For Each clause is true,I guess variable @i.GroupName is not be caught correctly.

    You could test it in F12=>Console.

    If you still have questions,please post more code and some comments,so that I can understand your mean better.

    Best Regards.

    Yuki Tao

    Tuesday, February 5, 2019 2:13 AM
  • User-1422983141 posted

    No Error in google debugger.

    $.ajax({
            url: "_Materials",
            data: { id: selectedId },
            type: "POST",
            success: function (data) {
            debugger;
            alert(data);
             }
            
    When I hit the debugger in the jquery I get the expected data that should show up in the partial.

    <div id="test" Class="col-md-8">
                    @Html.Partial("_Materials")
            </div>
    I have no answer to this as yet. can I assign the data to the partial. 

    Tuesday, February 5, 2019 7:44 AM
  • User-1422983141 posted

    So just to recap.

    I have debug all the code in visual studio and it all works as expected with the partial view being updated with the correct data.

    Google shows no errors and the data returned by the jquery is also the same data sent to the partial view.

    My view with the partial view shows only 1 check box which is the default when the view is started and the partial never changes to many checkboxes.

    Tuesday, February 5, 2019 8:02 AM
  • User1520731567 posted

    Hi kvic,

    I think I find the problem.

    <div id="test" Class="col-md-8">
                    @Html.Partial("_Materials")
            </div>

    @Html.Partial just call _Materials.cshtml,it do not jump to _Materials action,

    so the Compiler can't recognize ViewData("Group"),ViewData("Group") has not been processed by action.

    I suggest you could try to change :

    @Html.Partial("_Materials")

    to:

    @Html.Action("_Materials", "ControllerName"); //you need have an action named _Materials which return PartialView(_Materials)

    If you have any questions,please post complete code,so that I can reproduce your issue.

    Best Regards.

    Yuki Tao

    Wednesday, February 6, 2019 8:35 AM
  • User-1422983141 posted

    Hi, thank you for your response. I have already tried your suggestion but it didn't work for me.

    I can make the partial view show me the data I was expecting by hard coding an ID value that the function expects to collect the data for displaying, but this on;y works when

    the index view starts up.

    I believe I am missing an event that will refresh the partial page when a selection is made on the index page

    Everything is working otherwise and have now used the jquery ajax call to update the div to display the data I expect.

    <div id="AttributeName" Class="col-md-8">
    
       
    </div>

    $.ajax({
        url: "_Materials",
        data: { id: selectedId },
        type: "POST",
        success: function (data) {
        $('div#AttributeName').html(data);
        alert("success");
       }
    });
    I feel the code below that I have used before is correct as _Materials is in the home controller folder and the _Materials partial 
    is the the views home folder. MVC will find these items by default.

    <div id="test" Class="col-md-8">
    @Html.Partial("_Materials")
    </div>

    Because the page is updating without refreshing because of ajax and I don't think I will need to call the partial anywhere else
    I am happy to use the code as is, but I'm not happy that I haven't found the solution to the problem.


    Wednesday, February 6, 2019 8:03 PM
  • User1520731567 posted

    Hi kvic,

    Actually,I'm not quite understand your code,because your ajax:

    $(function () {
                $('div#Categories a').click(function () {
                    selectedId = $(this).attr('id');
                    alert(selectedId);
    
                    $.ajax({
                        url: "_Materials",
                        data: { id: selectedId },
                        type: "POST",
                        success: function () {
                            alert("success");
                        }
                    });
    
                });
            });

    and 

    @Html.Partial("_Materials")

    And lack some other code.

    If you would like to find the solution to the problem,please post your complete code,so that I can reproduce your issue,such as: two views and two views' action...

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 7, 2019 2:35 AM