Question

So I have a for loop in my View that is supposed to render out the input boxes. Now inside these input boxes I want to put lables that disappear when you click on them. This is all simple. Now it's probably because my brain was wired for php first, and it has been difficult to get it to think in lambdas and object orientation, but I can't figure out how to do this:

@{ for (int i = 0; i < 3; i++)
               {
                   <div class="editor-label grid_2">User</div>
                   Model.Users[i].UserFirstName = "First Name";
                   Model.Users[i].UserLastName = "Last Name";
                   Model.Users[i].UserEmailAddress = "Email Address";
                <div class="grid_10">
                @Html.TextBoxFor(m => Model.Users[i].UserFirstName, new { @class = "user-input" })
                @Html.TextBoxFor(m => Model.Users[i].UserLastName, new { @class = "user-input" })
                @Html.TextBoxFor(m => Model.Users[i].UserEmailAddress, new { @class = "user-input-long" })
                @Html.CheckBoxFor(m => Model.Users[i].IsUserAdmin)
                <span>&nbsp;admin?</span>
                </div>
                <div class="clear">
                </div>
               }
            }

And initialize the values for the users.

And you're probably thinking "Of course that won't work. You're going to get a Null Reference Exception", and you would be correct.

I might need to initialize them somewhere else and I don't realize it but I'm just not sure. I've tried the [DefaultValue("First Name")] route and that doesn't work.

I'm probably thinking about this wrong, but my brain is already shot from trying to figure out how to wire up these events to the controller, so any help would be appreciated!

Was it helpful?

Solution

Now inside these input boxes I want to put lables that disappear when you click on them

You could use the HTML5 placeholder attribute:

@Html.TextBoxFor(
    m => m.Users[i].UserFirstName, 
    new { @class = "user-input", placeholder = "First Name" }
)

And for older browsers that do not support this attribute use javascript to add this functionality. Here's a blog post on this topic: http://davidwalsh.name/html5-placeholder

There are also examples how you could use metadata to implement this directly at your view model: https://stackoverflow.com/a/5824169/29407

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top