jerhinesmith
jerhinesmith

Reputation: 15492

ASP.NET MVC Readonly Field Based on Action in Partial View

When using a partial view in ASP.NET MVC to encapsulate the creating/editing markup, what is the best way to change which control gets rendered based on the action?

For example, I want to only allow an email address to be entered upon account creation (via a textbox) and then viewable (via plain HTML) when viewing the account.

In pseudo-code, I'm expecting something like this:

<% if(Action == Create) {
  Html.TextBox("EmailAddress")
} else { 
  Html.Encode(Model.Person.EmailAddress)
} %>

Any suggestions?

Upvotes: 1

Views: 2305

Answers (1)

LondonBasedEngineer
LondonBasedEngineer

Reputation: 665

You could use your own HTML Helper class to encapsulate the logic:

public static string DualModeTextBox(this HtmlHelper helper, ViewMode viewMode, string textBoxName, string textBoxValue)
{
  if (viewMode == ViewMode.Edit) {
    return System.Web.Mvc.Html.InputExtensions.TextBox(helper, textBoxName);
  } 
  //else
  return helper.Encode(textBoxValue);
}

For more complex tasks you could also consider MVC controls.

Upvotes: 2

Related Questions