@sect...">

$ (document) .ready () when partial view is loaded

I have a partial view page.

MyMainView.cshtml

<div> @Html.Partial("MyPartial") </div> @section pagespecific { <script type='text/javascript'> $(document).ready(function(){ console.log('Value is: ' + $('#MyModelField').val()); }); </script> } 

MyPartial.cshtml

 <div> @Html.HiddenFor(x => x.MyModelField) </div> 

The value of MyModelField in the model is True , however I get the following output in the browser console:

 Value is: undefined 

Why does this not raise the field? Shouldn't a partial view be added to the DOM before this fire?

If I change the value of $(document).ready() to $(window).load() , it will work as expected.

How can I achieve the desired behavior?

+6
source share
2 answers

Yes, that’s true, the reason is when your home is .ready ready. Thus, your page loads first, and it runs the jQuery .ready () function, and a partial presentation of the sequence is also performed on the server side.

Both differ in usability.

To stop or you want to run after a while.

  • Or you can do it in a partial view

or

  • Give a delay time of your duration

     $(document).ready(function(){ console.log('Value is: ' + $('#MyModelField').val()); setTimeout("$('#buttonid').click()", DelayDuration); }); 

    // DelayDuration means milisecond, 1000 milisecond = 1 sec

The same question asked here

JQuery events do not work with ASP.NET MVC partial views

Is it possible to run javascript function after partial view in Asp.net MVC?

+3
source

$(document).ready does not start until partial display, because the partial view is displayed on the server side. You are using the wrong identifier in jquery because @Html.HiddenFor(x => x.MyModelField) will not create an element with ID = "MyModelField". The element will have an identifier with a prefix, which depends on your model class name.

Inspect the item identifier in the browser tools (F12) and determine the real identifier.

Example: If you are modeling the name of the User class. The generated identifier will look like User_MyModelField

0
source

Source: https://habr.com/ru/post/980065/


All Articles