Call Jquery function inside razor's subviews

2020-05-01 08:22发布

I want to use such an activity $('#myModal').show();

The original calling plugin routine is as follows:

<script type="text/javascript">
$(document).ready(function() {
     $('#myButton').click(function(e) {
          e.preventDefault();
      $('#myModal').show();
     });
});
</script>

I put my code in the below section. Here $('#myModal').show({}); doesn't run

    @using (Html.BeginForm("Contact", "Home", FormMethod.Post, new { name = "send-contact", id = "contactform1" }))
    {       
            @Html.AntiForgeryToken()  

            if (!String.IsNullOrEmpty(stResult)) 
             {                
                 <text>
                        <div id="myModal" class="reveal-modal">
                             <h1>Modal Title</h1>
                             <p>Any content could go in here.</p>
                             <a class="close-reveal-modal">&#215;</a>
                        </div>

                     $('#myModal').show({}); // The desired function!
                 </text>

             }
     }

There are 2 problems on this approach within my code

  1. The JQuery library is located at the bottom line of the Master Page (_Layout) There's a wrapper over all the plugins inside the famous ready() function which is located there.

  2. As an alternative way I placed the $('#myModal').show(); inside the JQuery.ready() in the Wrapper which when it calls everything if it should have found the "#myModal" based on my conditions then it'll fire the function I desired. but again that won't fire.

I think this approach seems to be more logical and may be the only logical between these 2 approaches cause the first one the function isn't located in the JQuery ready function, and if I use another ready function here it's also wrong because of the duplicate of ready function.

1条回答
欢心
2楼-- · 2020-05-01 09:03

If you are including a Partial view called Foo.cshtml you could also create a partial view named FooScripts.cshtml and render that view where the rest of your scripts are getting loaded:

<h2>Main View</h2>

@Html.Partial("Foo")

...


@section scripts {
    @Scripts.Render("~/bundles/jquery")
    @Html.Partial("FooScripts")
}
查看更多
登录 后发表回答