Reputation: 2266
I'm working on a web app based on MVC 4, and I'm trying to do some work with HTML forms. I have several separate models in a view model, like so:
public class NewAccountViewModel
{
UserModel User { get; set; }
AccountModel Account { get; set; }
TicketModel Ticket { get; set; }
}
I then use this as a model for my view. The view also consists of partial views for each model. Each of these partial views also use the view model as their model, and I pass the view model instance from the main view like this:
@Html.Partial("~/Views/Account/_User.cshtml", Model)
Then in the partial views, I add fields such as:
@Html.TextBoxFor(m => m.User.Name)
In my POST handler, I accept the view model instance as a parameter, and I can work with the data submitted from the form there. The form is submitted using jQuery.post
, with $('#nameofmyform').serialize()
as the data.
This approach works just like expected. However, the coupling between the partial views and the view model is too tight. If I would like to use the User model in a different controller with a different view model, that wouldn't be possible since the partial view uses this specific view model.
So, what I attempted was this:
@Html.Partial("~/Views/Account/_User.cshtml", Model.User)
And then, using the actual model as the partial view's model, I bound the fields:
@Html.TextBoxFor(m => m.Name)
This works one-way, in that all of the fields are populated correctly with the data from the view model and the models it contains. However, on POST, the view model is not properly serialized back. By inspecting the data sent back from the form, I see that in the first approach where everything is bound to the view model, it serializes the form with data like this:
{ "User.Name" : "Blahblah" ...
While with the second approach, it just serializes the form by the model:
{ "Name" : "Blahblah" ...
With this, the model properties of the view model are all null values in the POST handler.
So, what I'm really wondering is this: is it possible to somehow prepend the property name from the view model so that it's properly serialized back in my view model? Would I need to do this in JavaScript/through jQuery, or can it be done in my .NET code?
Upvotes: 1
Views: 1528
Reputation: 10645
You could set the field prefix like so:
ViewData.TemplateInfo.HtmlFieldPrefix = "User";
Upvotes: 0
Reputation: 1038730
Use an editor template instead of a partial:
@Html.EditorFor(x => x.User, "_User")
and then define ~/Views/Shared/EditorTemplates/_User.cshtml
:
@model User
...
@Html.TextBoxFor(m => m.Name)
Now your input fields will be correctly named because contrary to partials, editor templates respect the navigational context.
Upvotes: 3