Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Reuse of View by two controller actions

'Add' and 'Edit' views are typically more or less identical. How can I reuse a View so that Foos/Add and Foos/Edit/[Id] both use it? What would the actions look like?

Thanks

like image 682
David Avatar asked May 17 '11 08:05

David


2 Answers

Simply specify the view name when calling the View() method like

public ViewResult Add() {
  //...
  return View("Foo");
}

public ViewResult Edit(int id) {
  //...
  var model = repository.get(id);
  return View("Foo", model);
}

Your view will have to handle null/empty model values for the Add action or you could populate your model with default values.

like image 93
David Glenn Avatar answered Oct 10 '22 05:10

David Glenn


You may want to consider using an Editor Template as opposed to reusing the same View. An Editor Template is a partial View that is used for editing and/or inserting data.

This would require separate views but the code would be minimal. The bulk of the code would be in the template which you would reuse for both the Add and Edit actions.

After you create your template, your Add View would look like (Razor):

@model Models.Foo    
<h2>Add</h2>
<p>
@Html.EditorFor(model => model)  // equivalent to EditorForModel()
</p>

And your Edit View would look like:

@model Models.Foo    
<h2>Edit</h2>
<p>
@Html.EditorFor(model => model)  // equivalent to EditorForModel()
</p>
like image 28
rycornell Avatar answered Oct 10 '22 07:10

rycornell