Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ASP.NET MVC, how to best avoid writing both the Add View and Edit View?

Tags:

c#

asp.net-mvc

The Add view and the Edit view are often incredibly similar that it is unwarranted to write 2 views. As the app evolves you would be making the same changes to both.

However, there are usually subtle differences. For instance, a field might be read-only once it's been added, and if that field is a DropDownList you no longer need that List in the ViewData.

So, should I create a view data class which contains all the information for both views, where, depending on the operation you're performing, certain properties will be null?
Should I include the operation in the view data as an enum?
Should I surround all the subtle differences with <% if( ViewData.Model.Op == Ops.Editing ) { %> ?

Or is there a better way?

like image 768
tgmdbm Avatar asked Aug 20 '08 20:08

tgmdbm


People also ask

Can one action method have multiple views?

Yes, it's possible. Just make sure your views have same view model. From a technical stand point, views don't have to have the same view model implemented within the same action. There's just as long as the controller passes in the expected type.


1 Answers

It's pretty easy really. Let's assume you're editing a blog post.

Here's your 2 actions for new/edit:

public class BlogController : Controller
{
   public ActionResult New()
   {
      var post = new Post();
      return View("Edit", post);
   }

   public ActionResult Edit(int id)
   {
      var post = _repository.Get(id);
      return View(post);
   }

   ....

}

And here's the view:

<% using(Html.Form("save")) { %>
<%= Html.Hidden("Id") %>

<label for="Title">Title</label>
<%= Html.TextBox("Title") %>

<label for="Body">Body</label>
<%= Html.TextArea("Body") %>

<%= Html.Submit("Submit") %>
<% } %>

And here's the Save action that the view submits to:

public ActionResult Save(int id, string title, string body)
{
   var post = id == 0 ? new Post() : _repository.Get(id);
   post.Title = title;
   post.Body = body;

   _repository.Save(post);

   return RedirectToAction("list");
}
like image 193
Ben Scheirman Avatar answered Sep 27 '22 20:09

Ben Scheirman