Sander Van Looverenhttps://blog.sandervanlooveren.be/
The story of a .NET developerArticulate, blogging built on Umbraco1070https://blog.sandervanlooveren.be/posts/mvc-best-practices-for-create-update/
ASP.NET MVCWebMVC best practices for Create & Update<p>In ASP.NET MVC you have lots of flexibility in writing your views, controllers and viewmodels. Anything is possible, which is great! But it also has a downside. Everyone finds there own way of doing things and when you are working in a team the codebase may become hard to maintain. I see many applications which have implemented the most basic operations such as Create and Update using 2 views and 2 viewmodels (sometimes 1 viewmodel if you are lucky). I think we can do better than that!</p>
<p>Lets keep the same functionalities and flexibility using only 1 view and 1 viewModel (and a baseViewModel). Additionaly we don't want an IF statement in our view to render the correct form action, this should be handled by our viewmodel.</p>
<h3>The setup</h3>
<p>We have a database that holds people that our application will use. We want to create new people and update existing ones. To keep it simple I have created a very basic Person class that looks like this:</p>
<pre class="cs">public class Person : IEntityWithId
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}</pre>
<p>This doesn't require any explanation except for the interface which is implemented. <br />Even though the name says it all here is the definition of IEntityWithId:</p>
<pre class="cs">public interface IEntityWithId
{
int Id { get; set; }
}</pre>
<p>I have created this interface because we will use it in our ViewModel.</p>
<h3>Creating the ViewModel</h3>
<p>Now we have the boring stuff sorted out, we can start with the interesting part!</p>
<p>Because we want to keep our code consistent, we want to reuse this workflow as much as possible. To make sure we do so, I have created a BaseViewModel.</p>
<pre class="cs"><span>public</span> <span>abstract</span> <span>class</span> <span>BaseEntityFormViewModel</span>&lt;<span>T</span>&gt; <span>where</span> <span>T</span> : <span>IEntityWithId</span>
{
<span>protected</span> <span>T</span> Entity { <span>get</span>; <span>set</span>; }
<span>public</span> <span>bool</span> IsUpdate =&gt; Entity.Id &gt; 0;
<span>///</span><span> </span><span>&lt;</span><span>summary</span><span>&gt;</span>
<span>///</span><span> Gets the action name based on the lambda supplied</span>
<span>///</span><span> </span><span>&lt;/</span><span>summary</span><span>&gt;</span>
<span>///</span><span> </span><span>&lt;</span><span>typeparam</span><span> name</span><span>=</span><span>"</span><span>TController</span><span>"</span><span>&gt;&lt;/</span><span>typeparam</span><span>&gt;</span>
<span>///</span><span> </span><span>&lt;</span><span>param</span><span> name</span><span>=</span><span>"</span>action<span>"</span><span>&gt;&lt;/</span><span>param</span><span>&gt;</span>
<span>///</span><span> </span><span>&lt;</span><span>returns</span><span>&gt;&lt;/</span><span>returns</span><span>&gt;</span>
<span>protected</span> <span>string</span> GetActionName&lt;<span>TController</span>&gt;(<span>Expression</span>&lt;<span>Func</span>&lt;<span>TController</span>, <span>ActionResult</span>&gt;&gt; action) <span>where</span> <span>TController</span> : <span>Controller</span>
{
<span>return</span> ((<span>MethodCallExpression</span>)action.Body).Method.Name;
}
}</pre>
<p>Using the generic T, we make sure this viewmodel can be used for all entities which implement IEntityWithId (see the alternative way if you don't like this dependancy). To have access to all the properties on our actual entity I have created a property Entity of type T. Additionally, I have added a property IsUpdate (Get only) that tells us if we are updating the entity or creating it.</p>
<p>The method GetActionName Will help us to determine which action of our controller will have to be called on form post. Thanks to the lambda input parameter of this method, we can avoid hard coding our method name. The way we use this method will become clear below.</p>
<p>Now lets define our PersonFormViewModel.</p>
<pre class="cs"><span>public</span> <span>class</span> <span>PersonFormViewModel</span> : <span>BaseEntityFormViewModel</span>&lt;<span>Person</span>&gt;
{
<span>//Create a strongly named property to use in our view</span>
<span>//If you are ok with Entity in your view, you can make that property public</span>
<span>public</span> <span>Person</span> Person
{
<span>get</span> { <span>return</span> Entity; }
<span>set</span> { Entity = <span>value</span>; }
}
<span>public</span> <span>string</span> ActionName
{
<span>get</span>
{
<span>return</span> IsUpdate
? GetActionName&lt;<span>PersonController</span>&gt;(c =&gt; c.Update(<span>null</span>))
: GetActionName&lt;<span>PersonController</span>&gt;(c =&gt; c.Create(<span>null</span>));
}
}
<span>public</span> PersonFormViewModel()
{
Person = <span>new</span> <span>Person</span>();
}
}</pre>
<p>In this ViewModel I have encapsulated the Entity property into Person just to make our code in the view a bit more readable. If you are ok with Entity than you can just remove that line and make the Entity property in our baseViewModel public.</p>
<p>The property ActionName is get only and will return which action we want to use from our controller. As you can see it uses the GetActionName method from our baseViewModel. We use our PersonController (See code below) For the TController parameter and then we define our lambda to tell our method which function we want to use. Don't worry about the null passed to the method in the lambda expression. This method will never be executed, we only want to use its signature. We return the name as a string so we can use it in Html.BeginForm() in our View.</p>
<h3>The PersonController</h3>
<p>Our controller is pretty straight forward. I have an Index method, and 2 create and update methods, 1 Get and 1 Post using the viewmodel we have just created.</p>
<pre class="cs"><span>public</span> <span>class</span> <span>PersonController</span> : <span>Controller</span>
{
<span>public</span> <span>ActionResult</span> Index()
{
<span>//</span><span>TODO get people</span>
<span>return</span> <span>View</span>();
}
<span>public</span> <span>ActionResult</span> Create()
{
<span>var</span> model = <span>new</span> <span>PersonFormViewModel</span>();
<span>return</span> View(<span>"PersonForm"</span>, model);
}
[<span>HttpPost</span>]
[<span>ValidateAntiForgeryToken</span>]
<span>public</span> <span>ActionResult</span> Create(<span>PersonFormViewModel</span> model)
{
<span>if</span> (!ModelState.IsValid)
<span>return</span> View(<span>"PersonForm"</span>, model);
<span>//</span><span>TODO create person</span>
<span>return</span> RedirectToAction(<span>"Index"</span>);
}
<span>public</span> <span>ActionResult</span> Update(<span>int</span> id)
{
<span>var</span> model = <span>new</span> <span>PersonFormViewModel</span>();
<span>//</span><span>TODO get person</span>
model.Person = <span>new</span> <span>Person</span>
{
Id = id,
Firstname = <span>"Sander"</span>,
Lastname = <span>"Van Looveren"</span>
};
<span>return</span> View(<span>"PersonForm"</span>, model);
}
[<span>HttpPost</span>]
[<span>ValidateAntiForgeryToken</span>]
<span>public</span> <span>ActionResult</span> Update(<span>PersonFormViewModel</span> model)
{
<span>if</span> (!ModelState.IsValid)
<span>return</span> View(<span>"PersonForm"</span>, model);
<span>//</span><span>TODO update person</span>
<span>return</span> RedirectToAction(<span>"Index"</span>);
}
}</pre>
<p>I have added some TODO's for you to implement because these things are beyond the scope of this post. If there is a demand for the actual data access using the UnitOfWork and repository pattern I can devote a post about that. So just let me know and I'll see what I can come up with!</p>
<p><strong>Important</strong>: if your entity is bigger and contains some fields which can't be edited by a user make sure you prevent your controller from over-posting! (For more info see this <a href="http://odetocode.com/Blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx" target="_blank" title="Prevent overposting">link</a>)</p>
<h3>Finally creating our view</h3>
<p>We got our viewmodel and controller all set up so, now its time to create our view.</p>
<pre class="xml">@model WebApp.ViewModels.PersonFormViewModel
@{
ViewBag.Title = Model.ActionName;
}
&lt;h2&gt;@ViewBag.Title.&lt;/h2&gt;
@using (Html.BeginForm(Model.ActionName, "Person", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
if (Model.IsUpdate)
{
@Html.HiddenFor(m =&gt; m.Person.Id)
}
&lt;div class="form-group"&gt;
@Html.LabelFor(m =&gt; m.Person.Firstname, new { @class = "col-md-2 control-label" })
&lt;div class="col-md-10"&gt;
@Html.TextBoxFor(m =&gt; m.Person.Firstname, new { @class = "form-control" })
@Html.ValidationMessageFor(m =&gt; m.Person.Firstname)
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="form-group"&gt;
@Html.LabelFor(m =&gt; m.Person.Lastname, new { @class = "col-md-2 control-label" })
&lt;div class="col-md-10"&gt;
@Html.TextBoxFor(m =&gt; m.Person.Lastname, new { @class = "form-control" })
@Html.ValidationMessageFor(m =&gt; m.Person.Lastname)
&lt;/div&gt;
&lt;/div&gt;
&lt;div class="form-group"&gt;
&lt;div class="col-md-offset-2 col-md-10"&gt;
&lt;input type="submit" class="btn btn-default" value="Save" /&gt;
&lt;/div&gt;
&lt;/div&gt;
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}</pre>
<p>In our view I have created a form using Html.BeginForm, and I have specified the action to post to using the property from our viewmodel. As you can see this produces a clean layout and insures the correct action will be called. There is 1 difference in the form depending on the action we are doing, and that is the hidden field for the Id of our person. I have added an IF statement (using our IsUpdate property) which will only add the hidden input if we are updating the Person.</p>
<p>We have created 1 clean view which will be reused for both create and update. In my option this is way better than having to maintain 2 different views and even 2 different viewmodels when we want to make changes to our entity. I hope this will help you guys with doing the most basic actions, and of course you can build upon this when you want to do more interesting things.</p>
<h3>An alternative way</h3>
<p>If you don't like to use the interface IEntityWithId or if your entities use different types for the Id, there is an other way of doing things. In that case we will use a different baseViewModel and of course edit our PersonFormViewModel.</p>
<pre class="cs">public abstract class BaseFormViewModel&lt;T&gt;
{
public bool IsUpdate =&gt; !GetId().Equals(default(T));
protected abstract T GetId();
/// &lt;summary&gt;
/// Gets the action name based on the lambda supplied
/// &lt;/summary&gt;
/// &lt;typeparam name="TController"&gt;&lt;/typeparam&gt;
/// &lt;param name="action"&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
protected string GetActionName&lt;TController&gt;(Expression&lt;Func&lt;TController, ActionResult&gt;&gt; action) where TController : Controller
{
return ((MethodCallExpression)action.Body).Method.Name;
}
}<span class="code cs"><br /></span></pre>
<p>In this new baseViewModel the T parameter no longer corresponds to the type of our entity, but to the type of the Id parameter of our entity. I have created an abstract method which will return the value of the id. Using this method we can check if the id equals to the default value or if it has been set. This way we can still determine if we are doing an update or creating a new entity, and our View doesn't have to be changed.</p>
<p>To make this post complete I have edited our PersonViewModel to use this new baseViewModel.</p>
<pre class="cs">public class PersonFormViewModel : BaseFormViewModel&lt;int&gt;
{
//public Person Person { get; set; }
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
protected override int GetId()
{
//return Person.Id;
return Id;
}
public string ActionName
{
get
{
return IsUpdate
? GetActionName&lt;PersonController&gt;(c =&gt; c.Update(null))
: GetActionName&lt;PersonController&gt;(c =&gt; c.Create(null));
}
}
}</pre>
<p>Here you can see that I have commented out the actual entity, and copied the properties from the entity which the user can edit. This way we don't have to worry about the over-posting issue I mentioned earlier. If this is not an issue for you, you can use the property for your entity instead. I just gave you 2 options, its up to you to decide which one fits your needs.</p>
<p>Thanks for reading! Hopefully this has given you some idea's on how to improve your views &amp; viewmodels in MVC. If you have any comments or suggestions, please share!</p>Mon, 13 Feb 2017 18:00:00 +01002017-02-13T18:00:00+01:00