DRY in ASP.NET MVC - detail mapping and editing 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 in the add / edit form. (If you look at the product information, if you have rights to it, the "Edit" link will appear, it should display the same form, but with the text field fields turned on.)

The Details view now 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 so that I can reuse it without putting too much logic in the view? For example, I would need to remove the disabled = "disabled" part (but the size part should stay there) to put everything inside the form, etc.

If this cannot be done, this is fine, I just try not to repeat the same thing several times if I need to change it (and I will).

+4
source share
2 answers

You can always pass a value indicating which mode you are in, or what privileges you have:

 ViewData.Model.CanEdit 

This way you can create a composite class for your model, and not just use Product

 public class ProductViewData { public Product Product {get; set;} public bool CanEdit {get; set;} } 
+5
source

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

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

All Articles