admin管理员组

文章数量:1278787

In MVC4 I have an EditorFor field which represents a boolean and is rendered as a checkbox, I want to make other EditorFor fields change to uneditable if the checkbox is ticked. This would be simple in plain html but with razor syntax I'm not sure how to do this.

<div class="editor-field">
        @Html.EditorFor(model => model.Draw)
        @Html.ValidationMessageFor(model => model.Draw)
    </div>

<script type="text/javascript">
function validate() {
    if (document.getElementById('@Html.EditorFor(model => model.Draw)').checked) {
        alert("checked")
    } else {
        alert("You didn't check it! Let me check it for you.")
    }
}

Was trying to test it with that script but as I dont know the ID of the editorfor i'm unsure what to do.

In MVC4 I have an EditorFor field which represents a boolean and is rendered as a checkbox, I want to make other EditorFor fields change to uneditable if the checkbox is ticked. This would be simple in plain html but with razor syntax I'm not sure how to do this.

<div class="editor-field">
        @Html.EditorFor(model => model.Draw)
        @Html.ValidationMessageFor(model => model.Draw)
    </div>

<script type="text/javascript">
function validate() {
    if (document.getElementById('@Html.EditorFor(model => model.Draw)').checked) {
        alert("checked")
    } else {
        alert("You didn't check it! Let me check it for you.")
    }
}

Was trying to test it with that script but as I dont know the ID of the editorfor i'm unsure what to do.

Share Improve this question edited Jan 31, 2013 at 14:33 tpeczek 24.1k3 gold badges77 silver badges78 bronze badges asked Jan 31, 2013 at 13:18 Robert PallinRobert Pallin 1393 gold badges3 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

If you use CheckBoxFor instead of EditorFor (which is a generic helper), you can easily add HTML attributes through a method overload. Adding an ID allows you to access it from your JavaScript.

<div class="editor-field">
    @Html.CheckBoxFor(model => model.Draw, new { ID = "cbxDraw" })
    @Html.ValidationMessageFor(model => model.Draw)
</div>

<script type="text/javascript">
$(document).ready(function() {
    $('#cbxDraw').on('change', function() {
        var $cbx = $(this),
            isChecked = $cbx.is(':checked');

        $cbx.closest('.editor-field')
            .siblings()
            .find(':input')
                .prop('disabled', isChecked);
    });
});
</script>

(Note: This example uses jQuery)

ASP.NET MVC 4 has new NameExtensions class which provides IdFor and NameFor methods. You can use it like this:

document.getElementById('@Html.IdFor(model => model.Draw)')

本文标签: aspnet mvcUsing Javascript on EditorFor FieldsStack Overflow