Reputation: 3
I'm using .net MVC. I have some values in a form like:
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
On the controller, I get the data like:
public ActionResult NovaPessoa(Person person)
{
The problem is that I just can get values that I have placed the @Html.TextBoxFor
markup.
All the other complex information, like person.ContactInformation
is lost after submiting and I can't use the SaveChanges
in Entity Framework, because it will give me an invalid object after using the Atach
method.
The question is: Do I need to use the @Html.TextBoxFor
markup for all my model properties, even if I'm not using then to display anything, just to have them on Controller?
Upvotes: 0
Views: 126
Reputation: 65049
You are correct. What people (incorrectly) do normally, is use HiddenFor
:
@Html.HiddenFor(model => model.ContactInformation)
What you should be doing, is cutting down your model into a view model with only the appropriate properties.
So, don't use this model:
public class PersonVM {
public int PersonId { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string ContactInformation { get; set; }
}
..if all you're doing is updating the contact information. Instead, create a new class for your model:
public class PersonContactInfoEditVM {
public int PersonId { get; set; }
public string ContactInformation { get; set; }
}
That's all you need. This saves you from creating invalid objects when you don't add 30 HiddenFor
elements to your page .. resulting in very broken data.
You might be thinking "ugggghhhh, all that manual mapping from PersonContactInfoEditVM
to Person
... I don't want to be writing that sort of code". No one does.. which is why the following libraries exist:
Upvotes: 1