I have a page that has a partial view withing it.
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 into the browser console:
Value is: undefined
Why isn't this picking up the field? Shouldn't the partial view have been added to the DOM before this fires?
If I change the $(document).ready()
to $(window).load()
it works as expected.
How can I achieve the desired behavior?
Yes, you can include multiple ready event handlers on the page. You can put them in the site master, partial views, and view page itself -- as many as you need.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
Yes it is true, the reason is whenever your dom is ready .ready
is fired. So your page is loaded first and it fires the jquery .ready
function() , while the sequentially execution partial view also execute at server side.
Both are different in the usability.
To stop or you want to execute after some time.
or
Give the delay time of your duration
$(document).ready(function(){
console.log('Value is: ' + $('#MyModelField').val());
setTimeout("$('#buttonid').click()", DelayDuration);
});
//DelayDuration means give milisecond value, 1000 milisecond = 1 sec
The same question asked here
JQuery events don't work with ASP.NET MVC Partial Views
Is it possible to kick off a javascript function after a partial view renders in MVC Asp.net?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With