2

I'm trying out jQuery in an MVC3 ASP.NET app but I'm struggling with the model aspects.

This is not working:

I've declared a TextBox Watermark library:

<script src="../../Scripts/jquery.tinywatermark-3.1.0.js" type="text/javascript"></script>

I then add my jQuery:

<script type="text/javascript">
    $(function () {
        $('.watermarked').watermark('watermark', 'Please Enter...');
    });
</script>

Then add the watermarked class to my div model field:

<div class="editor-field">
     @Html.EditorFor(model => model.SchemeName, new { @class = "watermarked" }) 
    @*<input class="watermarked"  @Html.EditorFor(model => model.SchemeName) />*@
    @Html.ValidationMessageFor(model => model.SchemeName)

If I uncomment the section it sort of works but I want to maintain the Razor model, any ideas, anyone?

2 Answers 2

3

The following line:

@Html.EditorFor(model => model.SchemeName, new { @class = "watermarked" })

doesn't do what you think it does. The second argument that you are passing to the EditorFor helper doesn't do what you think it does. It sends additional view data to the custom editor template. It doesn't apply any html attributes as you might be thinking. If you want this syntax to work you have the possibility to write a custom metadata provider and a custom editor template as illustrated in the following article.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Darin, Can I add the Class some other way? not sure how to get this to work!
Sure, you could write a custom metadata provider and a custom editor templates. I have updated my answer with a link to an article illustrating this concept in action.
Hmmm, this doesn't work either :( @Html.EditorFor(model => model.SchemeName, htmlAttributes: new { @class = "watermarked" })
As I said in my answer, the second argument of the EditorFor helper is not htmlAttributes. Do not try to pass html attributes to it as this is not going to ever work. You need much more to do to make it work => a custom metadata provider and a custom editor template. Did you read the article I've linked to?
Sorry Darin, I didn't notice you had added to your comment, I'll go look, Cheers!
1

I'm not sure what the preference for EditorFor() is that you need it but this should work just fine

@Html.TextBoxFor(model => model.SchemeName, new { @class = "watermarked" })

1 Comment

Thanks CD, that works, I just accepted the default template when creating the view

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.