1

I have created a partial view where i am using Bootstrap Glyphicon (collapse and expand) upon button click. But, the JavaScript code is not working here as I am dynamically adding Partial View using Ajax.

My Controller:

 public ActionResult DisplaySearchResults(int Id)
   {
    if (Id == 317)
       {
         return PartialView("~/Views/Shared/_PartialReportViews/StatisticalReport.cshtml");
       }
     else if (Id == 318)
       {
        return PartialView("~/Views/Shared/_PartialReportViews/Leading_Progeny.cshtml");
       }        
       return PartialView();
    }

My main View:

<div class="container">
<div id="partial"></div>

@section scripts{
    <script type="text/javascript">
        $('.search').click(function () {
            var id = $(this).data('assigned-id');
            var route = '@Url.Action("DisplaySearchResults", "Home")?id=' + id;
            $('#partial').load(route);   
        });
        var partial = $('#partial');
        partial.on('shown.bs.collapse', '.collapse', function () {
            $(this).closest('.group').find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
        }).on('hidden.bs.collapse', '.collapse', function () {
            $(this).closest('.group').find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
        });
    </script>
}
    <input class="search btn-info" type="button" value="Search" data-assigned-id="@item.ProductId" />
</div>

My Partial View

<div class="group">
    <button type="button" value="Button" data-toggle="collapse" data-target="#demo">
        <span class="glyphicon glyphicon-plus"></span>
    </button>
    <div class="container">
        <div class="row">
            <div class=" col-sm-12">            
                @using (Html.BeginForm("Report", "Home", FormMethod.Get))
                {
                    @Html.DisplayNameFor(m => m.Name)
                    @Html.TextBoxFor(m => m.Name, new { @class = "form-control", style = "width: 155px", placeholder = Html.DisplayNameFor(n => n.Name})
                    @Html.HiddenFor(m => m.Id)
                }
            </div>
            <div id="demo" class="collapse">
                <div class="col-sm-12">
                    @Html.DisplayNameFor(model => model.StartDate)
                    @Html.TextBoxFor(m => m.StartDate, new { @class = "form-control", style = "width: 155px", placeholder = Html.DisplayNameFor(n => n.StartDate) })
                    @Html.DisplayNameFor(model => model.Distance)
                    @Html.DropDownListFor(m => m.Distance, Model.DistanceOptions, "All", new { @class = "form-control", style = "width: 150px;" })
                </div>
            </div>
        </div>
    </div>
</div>

Can anyone please guide me where I am going wrong?

9
  • "But, the JavaScript code is not working here." - What does this mean? You get errors? If so, which ones? Commented Dec 12, 2017 at 21:42
  • @FailedUnitTest, I mean, When I click on the button in browser console, the javaScipt code is not executing. There is no such error. It is not going inside JavaScript function. Commented Dec 12, 2017 at 21:46
  • Scripts should never be in partial views. Start by moving the script to the main view (and ensure its loaded after jquery.js) Commented Dec 12, 2017 at 22:47
  • And how is that partial being rendered? Is it loaded after the main view has been rendered (e.g. using ajax)? Commented Dec 12, 2017 at 22:49
  • @StephenMuecke, It is loaded after main view has been rendered. Commented Dec 12, 2017 at 22:52

2 Answers 2

1

I believe you need to add the event listeners to the button instead. This appears to work.

        $('#demo').on('shown.bs.collapse', function () { 
            debugger;
            $(this).parent().prev('button').find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
        }).on('hidden.bs.collapse', function () {
            debugger;
            console.log('hide');
            $(this).parent().prev('button').find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
        });

And here is a link to fiddle that simply outputs 'show' or 'hide' to your console.log to show that it does indeed work. https://jsfiddle.net/wuvrp0y3/

Edit for clarification: You may need to change the selectors used within the functions, as the context of $(this) is no longer valid.

After comments;

It appears that you are calling the $(document).ready function only once, on page load (as you should be), and the -new- partial view does not have the events registered.

I would suggest creating a function that sets up those events (also turning off those events beforehand, as so;

function SetUpCollapse(){
        $('.collapse').off('click shown.bs.collapse hidden.bs.collapse');
        //This is necessary to prevent multiple calls from triggering this event multiple times.
        $('.collapse').on('click', 'shown.bs.collapse', function () {
            debugger;
            $(this).parent().prev('button').find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
        }).on('hidden.bs.collapse', function () {
            debugger;
            console.log('hide');
            $(this).parent().prev('button').find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
        });
}

Then, in your document.ready, call it;

$(document).ready(function(){
SetUpCollapse();
});

I assume you use ajax to load your partial view. However you do that, there should be an 'on completion' function, simply call that same function within that as well.

IE,

  $.ajax({
    url: "SomeURLHere",
    type: "POST",
    data: {data: data},
    dataType: "html",
    success: function (html) {
      //append html
      SetUpCollapse();
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
  });
Sign up to request clarification or add additional context in comments.

6 Comments

The code which i have pasted here works in main View but not in Partial View. So my question here is how to make it functional in partial view.
Can you please verify that your document.ready function is completing? If it is not, you could potentially work around the document.ready with a window.load instead.
document.ready is completing upon button click in main view which opens partial View. In Partial View, If I click on glyphicon then nothing happens.
Ah, that makes sense. It sounds like you are not calling the function AFTER the partial view is placed in the page. I will update my answer accordingly.
this code is still not working. Please have a look on my main view script code. @section scripts{ <script type="text/javascript"> $('.search').click(function () { var id = $(this).data('assigned-id'); var route = '@Url.Action("DisplaySearchResults", "Home")?id=' + id; $('#partial').load(route); }); </script> }
|
0

Are your event listeners possibly missing an event?

from

$('.collapse').on('shown.bs.collapse', function () {

to

$('.collapse').on('click', '.shown.bs.collapse', function () {

2 Comments

It might be dependent on the selectors matching the html. You could just try attaching the click listener only to collapse. The secondary selectors work as filters, so if those don't exist in HTML, then it won't fire. Try this and see if you can get any console output. $('.collapse').on('click', function () { console.log('hit'); }); Also if you could edit your question and post some of the compiled HTML, that might help with troubleshooting
The same code works in main view. Please suggest me why the same JavaScript is not working here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.