'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
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With