简体   繁体   中英

MVC Razor HTML helpers not rendered when $(document).ready(

I just noticed that my MVC Razor HTML helpers arent rendered (in DOM) when my javascript is calling $(document).ready(function.... So when I put code that is dependent on DOM objects in the document ready, it doesnt find the DOM objects.

Javascript

$(document).ready(function () {
    $('input:radio,select').change(function () {
        DO STUFF...

HTML helpers

@Html.RadioButtonList(m => m.ItemType, new SelectList(Model.ItemTypes, "Name", "Name")

another

@Html.DropDownListFor(n => n.ApartmentFloor, new SelectList(Model.ApartmentFloors, "Id", "Floor"), new { @id = "floorsSelect", @class = "exists" })

Normally, the radiobuttons and the dropdowns should get a .change function, but since they arent rendered yet when the .change is added, they dont get that function.

Is there a way to get "on html helpers ready" instead of "on document ready"?

Edit :

People have pointed out that HTML helpers run on the server, before the client starts to render, thus should be finished before as well. This doesn't seem to be the case, since, when I debug the JS "on document ready", the HTML helpers objects aren't rendered yet but the rest of the page is.

So the question remains, is there a way to add a "on load" function the HTML helper object, or to add a "change" function directly from the cshtml file with razor syntax?

Try registering the event like this,

      $('input:radio,select').on("change" ,function () { }) ;

Hope this shall help.

I realized that I never posted the solution to my problem. Even though people pointed out that HTML helpers should be rendered before document ready, this didnt seem to be the case for me. So what I did was to add the event handler directly on the HTML helper instead:

@Html.RadioButtonList(m => m.MyObject, new SelectList(Model.MyObjects, "Name", "Name"), "inputChangeHandler($(this));")

Works great =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM