tags:

views:

4271

answers:

3

Currently when I want to set html attributes like maxlength and autocomplete, I have to use the following syntax:

<%= Html.TextBox("username", ViewData["username"], new { maxlength = 20, autocomplete = "off" }) %>

Is there any way to do this without having to explicitly set the ViewData["username"] portion? In other words, I want to rely on the helper method's automatic loading routine rather than having to explicitly tell it which field to load up from the ViewData.

A: 

yes but you have to use ViewData.Model instead of ViewData.Item()

the code in your controller should look like this (sry 4 VB.NET code)

Function Index()
    ViewData("Title") = "Home Page"
    ViewData("Message") = "Welcome to ASP.NET MVC!"

    Dim user As New User

    Return View(user)
End Function

now you can do this in the view

<%=Html.TextBox("username", Nothing, New With {.maxlength = 30})%>

note that the user object has a public property username

hth

marc.d
+9  A: 

Just pass "null" as second parameter:

<%= Html.TextBox("username", null, new { maxlength = 20, autocomplete = "off" }) %>
veggerby
A: 

I used construction as below:

<%= Html.TextBox("username", "", new { @maxlength = "20", @autocomplete = "off" }) %>
omoto
This doesn't persist the viewstate. What if after submission, there was a validation error that I wanted to display to the user? Doing this would clear out the "username" textbox and force the user to start over from scratch.
Kevin Pang