0

I've researched on answers on this topic for MVC 3 & MVC 4 and I was hoping to find a solution for MVC 5. I have a view which loads partial view via ajax. Within the view, I have all my javascript logic defined (@section Scripts) there as I can't have any in my partial view. The problem is, within my partial view, I wish to call a javascript function that is defined within the view upon success.

Below is my view and partial view

MyView.cshtml

@section Scripts
{
    @Scripts.Render("~/plugins/myplugins")
    <script>
        function callFunctionOutsideThisPartialView() {
        //... This doesn't get called
        }
    </script>
}

MyPartialView.cshtml

@using (Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
    HttpMethod = "POST", 
    InsertionMode = InsertionMode.Replace, 
    UpdateTargetId = "divForPartialView", 
    OnSuccess = "callFunctionOutsideThisPartialView()"
}, new { @class = "form-inline" }))
{
    // Partial View here
}

What is the correct way to access javascript functions that are outside of the partial view in MVC 5?

Community
  • 1
  • 1
usr4896260
  • 1,427
  • 3
  • 27
  • 50
  • 1
    the idea of partial view is to reuse html code. no matter how complex you have made your partial view rendering to be. All the partial views will eventually get put into your layout, rendered as 1 piece of html. When your html gets rendered in your browser, that is where your js comes into play. As long as the js function your partial view is referencing eventually gets loaded in your page. you should be ok – Ji_in_coding May 16 '16 at 20:13
  • That's what I tried, however, the javascript in OnSucess is not called as the console says that the function doesn't exist. – usr4896260 May 16 '16 at 20:58
  • 1
    @Ji_in_coding is correct. Unless the sample code you pasted is not the actual architecture you're using, the function `callFunctionOutsideThisPartialView()` should be declared in the global scope. – Mark C. May 16 '16 at 21:23

1 Answers1

1

If I'm remembering correctly, just render you partial view in a normal view and load that normal view via ajax call.Add you jquery's to normal view also.

Yepo
  • 134
  • 4