Edwardo
Edwardo

Reputation: 902

How do I make an Html.TextBox either read-only or invisible?

Complete n00b to MVC. I've been asked to knock up a quick contact management system for my running club. It's all working ok, based on the MVC Contact Manager template:

http://www.asp.net/mvc/tutorials/older-versions/contact-manager/iteration-1-create-the-application-cs

I've adapted this to link to the club's SQL Server Membership database. However, it exposes the Primary Key of the Member table on the Edit form. I don't mind it being visible but it MUST be read-only (though it would be better if it were not visible).

The markup generated for the View is

<%= Html.TextBox("ID") %>

I've tried adding attributes such as read-only, visible etc. but though it compiles, it blows up when it's rendered.

<%= Html.TextBox("ID"); Visible = false %>

I'm pretty sure this can be done but I have run out of Google hits on this!

Thanks

Edward

Upvotes: 0

Views: 326

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you can disable it,so that it can't be editable:

<%= Html.TextBox("ID", "", new {@disabled="disabled"}) %>

Upvotes: 0

Andrei V
Andrei V

Reputation: 7476

You can specify the HTML properties and set the input as readonly. This will add the appropriate HTML markup in order to make the text box read only:

<%= Html.TextBox("ID", "", new { @readonly = "readonly" }) %>

This method uses the Html.TextBox(String, Object, Object) overload, with the first parameter being the name of the input, the second being the value and the third the dictionary containing the HTML properties.

EDIT: As DGibbs pointed out, readonly is a reserved keyword and must be preceded by @. However, I find it better to create a Dictionary object that contains the HTML properties. This is also what the MVC prefers since it converts all the objects into Dictionary<string, object>:

Dictionary<string, object> htmlProperties = new Dictionary<string, object>();
htmlProperties.Add("readonly", "readonly");

You can then just specify it as the third parameter, using the Html.TextBox(String, Object, IDictionary) overload:

<%= Html.TextBox("ID", "", htmlProperties) %>

Upvotes: 2

Related Questions