locked
@foreach with jQuery No Results RRS feed

  • Question

  • User-1641868886 posted

    I have an MVC @foreach loop...using jQuery to pass in a parameter to initiate the table. First is the MVC razor view:

    <div class="row">
            <div id="CodesDiv" class="col-md-6" style="min-height:200px">
            @if (Model != null)
            {
                <div class="col-md-12">
                    <table class="table" id="CodesListTbl">
                        <tr>
    
                            <th>
                                @Html.DisplayNameFor(model => model.Code)
                            </th>
                            <th>
                                @Html.DisplayNameFor(model => model.Description)
                            </th>
    
                        </tr>
    
                        
                        @foreach (var item in Model)
    
                        {
                            
                            <tr>
    
                                <td>
                                    @Html.DisplayFor(modelItem => item.Code)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.Description)
                                </td>
    
                            </tr>
                        }
    
                    </table>
                </div>
            }
    
            </div>
            <div class="col-md-6">
                <span class="lead">Enter a Description or keyword:</span><br/>
                <input type="text" id="Description" /><input type="button" style="margin-top:6px" class="btn btn-success" id="CodeFind" value="View Codes" />
    
            </div>
        </div>

    ...and here is the script:

    $("#CodeFind").click(function () {
            $.validator.unobtrusive.parse("#Description");
            
            var Description = $("#Description").val();
            $.ajax({
                type: "Get",
                url: "/GrocBills/GetCodeListForDescr?Description" + Description,
                data: { Description: Description },
                dataType: "Json",
                success: function (response) {
                    $("#CodesListTbl").append(response);
                    
                }
            });
        })
    

    All the way down the script I am seeing the array of objects based on the passed parameter "Description". In script debugging,   when I hover over "(response)" I see the array...but it does not render in the div where the table resides. Not sure if I have a jQuery or a html/razor problem.

    Thanks for looking and any suggestions.

    RC

    Wednesday, October 2, 2019 4:05 PM

Answers

All replies

  • User475983607 posted

    The code is too confusing to guess the intended functionality.  The AJAX method is configured to expect a JSON response but the successful handler is trying to append HTML to the end of a table.  The AJAX query string is malformed, it is missing the "=".  You've also defined the data property.  Use either the URL or data not both.

    $("#CodeFind").click(function () {
            $.validator.unobtrusive.parse("#Description");
            
            var Description = $("#Description").val();
            $.ajax({
                type: "Get",
                url: "/GrocBills/GetCodeListForDescr?Description=" + Description,
                data: { Description: Description },
                dataType: "Json",
                success: function (response) {
                    $("#CodesListTbl").append(response);
                    
                }
            });
        })

    We cannot see the /GrocBills/GetCodeListForDescr action and therefore unable to comment.  Please take a moment to review your code and try reading the AJAX reference documentation so you understand the configuration; https://api.jquery.com/jquery.ajax/

    Wednesday, October 2, 2019 5:58 PM
  • User-1641868886 posted

    Thanks for the response. Okay, a couple of rookie mistakes fixed, I believe:

    $("#CodeFind").click(function () {
            $.validator.unobtrusive.parse("#Description");
            
            var Description = $("#Description").val();
            $.ajax({
                type: "Get",
                url: "/GrocBills/GetCodeListForDescr?Description=" + Description,
                dataType: "json",                                                <<  (**tried changing dataType to html**)
                success: function (response) {
                    $("#CodesListTbl").html(response);            <<  (***tried changing to .text(response)***)
                }
            });
        })

    ...and here's the controller action:

    public JsonResult GetCodeListForDescr (string Description)
                {
    
                DynamicParameters param = new DynamicParameters();
                param.Add("@Description", Description);
    
                var model = DataAccess.ReturnList<CodeViewModel>("spCodes_ViewByDesc", param).ToList<CodeViewModel>();
    
                return Json(model, JsonRequestBehavior.AllowGet);
            }

    ..."DataAccess" is my Dapper helper class of functions.

    Again, I'm getting a full array with multiple rows of data in the response. I just can't get the data into the table in the razor view, and don't know why. Trying several iterations of syntax...trying to learn by trial and error. Something formatted wrong in the view?

    Thanks again for any suggestions.

    RC

    Wednesday, October 2, 2019 9:35 PM
  • User475983607 posted

    Okay, Now that I can see the rest of the code.  This bit of code is okay.

     

           $.ajax({
                type: "Get",
                url: "/GrocBills/GetCodeListForDescr?Description=" + Description,
                dataType: "json",

    This bit is wrong.

                success: function (response) {
                    $("#CodesListTbl").html(response);            <<  (***tried changing to .text(response)***)
                }

    It seems you are under the impression jQuery will somehow map a JSON response to your HTML table.  Well, that's not going to work.  You need to write JavaScript to update the table html.

    Fortunately, adding rows to a table is pretty common and you can find many examples on the web.  Below are a few.

    https://stackoverflow.com/questions/171027/add-table-row-in-jquery

    https://stackoverflow.com/questions/17724017/using-jquery-to-build-table-rows-from-ajax-responsejson

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 2, 2019 10:41 PM
  • User-1641868886 posted

    Thanks, really appreciate your suggestion...and patience! I slightly modified from an example in the second link you posted. I figured out to eliminate the "@foreach" from my razor view. So here's the new success function that renders response results in the tbody:

    $("#CodeFind").click(function () {
            $.validator.unobtrusive.parse("#Description");
            
            var Description = $("#Description").val();
            $.ajax({
                type: "Get",
                url: "/GrocBills/GetCodeListForDescr?Description=" + Description,
                dataType: "json",
                success: function (response) {
                    var trHTML = '';
                    $.each(response, function (i, item) {
                        trHTML += '<tr><td>' + item.Code + '</td><td>' + item.Description + '</td></tr>';
                    });
                    $("#CodesListTbl").append(trHTML);
                }
            });
        })

    ...now if you can steer me to an example that within the javascript, formats the 'item.code' as a clickable link, I'll try to incorporate that as well. I'll be searching for it in meantime.

    Thanks again!

    RC

    Thursday, October 3, 2019 7:41 PM
  • User-474980206 posted

    it just html, use <a href="link">click me<a>

    Thursday, October 3, 2019 7:51 PM
  • User475983607 posted

    ReidMelSam

    now if you can steer me to an example that within the javascript, formats the 'item.code' as a clickable link

    Use a link or Url helper.  I think this is correct or at least close.  You'll need to replace action and controller with your stuff.

    '<tr><td><a href="@Url.Action("action", "controller")?code=' + item.Code + '">'  + item.Code + '</a></td><td>' + item.Description + '</td></tr>'

    Thursday, October 3, 2019 8:00 PM
  • User-1641868886 posted

    Thanks again...to both of you. I did look and right away found an example or two.

    My original view, "Index" has a "Code" textbox. If the user needs to "lookup" a code, this view (partial) is a Popup dialog they can invoke with a button.

    The link is for the user to click their chosen "Code", the dialog box will close, and the chosen "Code" will be used to fill in the original "Code" textbox on the "Index" view. So I have a bit more work to do.

    Thanks again!

    RC

    Thursday, October 3, 2019 8:22 PM