Marcel Popescu
Marcel Popescu

Reputation: 3341

DRY in ASP.NET MVC - details display vs. edit form

I am trying to learn ASP.NET MVC and I hit this problem: I have a "view product details" form that I want to reuse as an add/edit form. (When you look at the product details, if you have the rights to do it an Edit link should appear; it should redisplay the same form, but with the textbox fields enabled this time.)

Right now the Details view looks something like this:

<% var product = ViewData.Model; %>
<table>
  <tr>
    <td>Name</td>
  </tr>
  <tr>
    <td><%= Html.TextBox("Name", product.Name, new { size = "50", disabled = "disabled"})%></td>
  </tr>

Is there a way I could reuse it without putting too much logic in the view? For example, I will need to remove the disabled = "disabled" part (but the size part needs to stay there), to put everything inside a form and so on.

If it can't be done, that's fine, I'm just trying not to repeat the same thing several times in case I need to change it (and I will).

Upvotes: 4

Views: 1648

Answers (2)

Tim Scott
Tim Scott

Reputation: 15205

Using MvcContrib.FluentHtml you can do like this (enhancing Todd Smith's suggestion):

<%=this.TextBox(x => x.Name).Size(50).Disabled(ViewData.Model.CanEdit)%>

Upvotes: 10

Todd Smith
Todd Smith

Reputation: 17272

You can always pass in a value indicating what mode you're in or what privileges you have:

ViewData.Model.CanEdit

So you might want to create a composite class for your model instead of just using Product

public class ProductViewData
{
    public Product Product {get; set;}
    public bool CanEdit {get; set;}
}

Upvotes: 5

Related Questions