Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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).

like image 438
Marcel Popescu Avatar asked Dec 08 '22 08:12

Marcel Popescu


2 Answers

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

<%=this.TextBox(x => x.Name).Size(50).Disabled(ViewData.Model.CanEdit)%>
like image 88
Tim Scott Avatar answered Dec 09 '22 20:12

Tim Scott


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;}
}
like image 36
Todd Smith Avatar answered Dec 09 '22 22:12

Todd Smith