Reputation: 3733
I am quite new to C# MVC. I have been building ViewModels for a while, tacking data to it on the backend and presenting the VM in the view (Razor). Now however, I am trying to create a Razor-form with validation, and learned through some reading that the Model with which we are providing input-fields for is implicitly equal to the ViewModel specified in the top of the Razor document with the @model Path.To.SomeVM
annotation.
My worry is that my VM is currently holding a lot of information, not just an empty object skeleton to which I wish to attach data and pass to the controller for validation.
Take the following pseudo-VM:
namespace Frontend.Models.VM.User
public class VMUserCreate {
public List<Group> PermissionGroups { get; set; }
public Person Manager { get; set; }
public Person NewUser { get; set; }
}
Now, consider the view
@model Frontend.Models.VM.User.VMUserCreate
// Print all groups
// Print current Manager
@using (Html.BeginForm("Create", "User", FormMethod.Post))
{
@Html.TextBoxFor(model => model.NewUser.Firstname)
@Html.PasswordFor(model => model.NewUser.Password)
}
Now, I presume that upon submission of this form, I would pass the entire ViewModel to the action, and not just the @model.NewUser
object. Given a situation where the entire @model holds a ton of information, is this a sensible way of doing things? Is there perhaps a way I can explicitly specify the model to use in the form?
.NET Version: 4.5
MVC Version: 5.2.3
Upvotes: 2
Views: 90
Reputation: 239350
It doesn't work the way you think. The only thing that exists after posting is the data that was posted. In your example, you'd end up in your post action with an instance of your view model with everything null except the NewUser
property, since only properties on that object were posted.
This is actually how you want it. The other members are not being modified and therefore should not participate in the post. However, it does mean that you need to repopulate these properties from the database again after post, should you need to redisplay the form due to an error or something.
Upvotes: 3
Reputation: 11595
Have you considered partintioning your form into separate views/regions that have their own view-model?
I have done this before when my view became overwelmingly complex. As a result, I think if you break your monolithic view down into regions, you will be better able to support the Single Responsibility Principle.
Upvotes: 0