views:

37

answers:

2

I've mostly worked in MVC1. I'm now working with some MVC2 code. I have fields with Strongly Typed Html Helpers like:

        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Contract.client_name)%>
            <%: Html.ValidationMessageFor(model => model.Contract.client_name) %>
        </div>

How do I access this field in jquery? I previously would have:

$('#client_name').val();

or in jquery .validate:

$('form').validate({
            rules: {
                client_name: "required"
            },
            messages: {
                client_name: "Client Name is required"
            }
});
+1  A: 

You have a couple of options here:

Use a class selector.

For the .validate you could try this:

$('form').validate({
    rules: {
        'Contract.client_name': "required"
    },
    messages: {
        'Contract.client_name': "Client Name is required"
    }
});

or simply override the id:

<%: Html.TextBoxFor(model => model.Contract.client_name, new { id = "client_name" })%>
Darin Dimitrov
Thanks! That did the trick
RememberME
A: 

Darin's answer works, but there is better way to do it. in MVC Futures assembly there's HtmlHelper extension method for just that.

$('#<%: Html.IdFor(m => m.Contract.client_name) %>').val();

Update for validate:

$('form').validate({
    rules: {
        '<%:Html.IdFor(m => m.Contract.client_name) %>': { required : true }
    },
    messages: {
        '<%:Html.IdFor(m => m.Contract.client_name) %>': { required: "Client Name is required" }
    }
});

I never used this, and I'm not sure whether it wants id or name of the element. If it's name, use Html.NameFor() instead.

Necros
How would that work for the validate?
RememberME
@RememberME - see update.
Necros
@Necros, javascript files are (should be) separate files from the views in order to make them cacheable and improve performance so this technique wouldn't work (you cannot use server tags in .js files).
Darin Dimitrov
@Darin - Putting javascript in separate files is a good practice, but so is not hardcoding field ids as magic strings. In this case (validation) i would forget about writing it in javascript, and rather use some MVC specific way of validation (built-in, xVal, fluent validation...) that in the end may, or may not use jquery validation and will generate javascript you need for you. Then you won't have to worry about this.
Necros