asp.net mvc how to pass full model from view to controller
asp.net, asp.net-mvc, c#
Solution
If you want the complete model to be submitted, then you need to include all the model properties in your form. You can do this using `@Html.HiddenFor(m => m.YourPropertyName)` if you don't want them to be displayed. I don't see any form tags in your code, but I assume there are some?
You already have validation on your model properties as you've used the [Required] DataAnnotations, so to check this on the server side, you need to check ModelState.Valid when you post the data to your controller.
public ActionResult SubmitMyForm(MyModel model)
{
if (ModelState.IsValid)
{
...
Response to comment:
the form would look something like this:
@using (Html.BeginForm())
{
<table>
...
</table>
}
The error is occurring because inside the `using` block, you don't need to prefix C# code with `@`. See this answer for an explanation.
Problem
I have such table in a view ``` <table class='sendemailtable'> @if (!string.IsNullOrEmpty(Model.CustomerName)) { <tr> <td style="font-size: 26px;"> @Html.Label(string.Empty, Model.CustomerName) </td> </tr> } <tr><td style="padding-top: 15px;">To:</td></tr> <tr> <td> @Html.TextBoxFor(m => m.EmailTo) @Html.ValidationMessageFor(m => m.EmailTo); </td> </tr> <tr><td style="padding-top: 15px;">Subject:</td></tr> <tr> <td style="font-size: 22px;"> @Html.TextBoxFor(m => m.EmailBody) </td> </tr> few more <button style="..." type="submit">SEND</button> </table> ``` These are not all items from model, it has some more ids which are not present in ui, have some property with only getter ``` public int OfferID; public int SomeOfferID; public int CustomerID; #region Email [Required] [DataType(DataType.EmailAddress)] [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect email")] public string EmailTo; private string emailBodyDefault; public string EmailBody { get { if (string.IsNullOrEmpty(emailBodyDefault)) emailBodyDefault = string.Format("Hi,{1}please take a look. Offer ID: {0}{1}{1}Thanks", SomeOfferID, Environment.NewLine); return emailBodyDefault; } set { emailBodyDefault = value; } } private string emailSubject; [Required] public string EmailSubject { get { if (string.IsNullOrEmpty(emailSubject)) emailSubject = string.Format("Offer ID: {0}", SomeOfferID); return emailSubject; } set { emailSubject = value; } } #endregion ``` I want to pass full my model to controller, to be able to send email from controller's action. Also need to validate user's email, and non-empty subject when user clicks send. How can i do this ?