Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready() firing before partial view is loaded

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?

like image 848
Alex Avatar asked Dec 23 '14 06:12

Alex


People also ask

Can we use document ready in partial view?

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.

What is $( document ready () function Why should you use it?

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.


1 Answers

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.

  • Either you can do this in partial view

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?

like image 121
Ajay2707 Avatar answered Sep 21 '22 01:09

Ajay2707