Pass an entire model on form submission

自古美人都是妖i 提交于 2019-12-03 09:51:05

The model will be passed to the controller in its entirety, but the values of properties that are not bound by input or hidden fields will be lost.

You have to either bind the properties in the form on the client-side, or re-fetch the entity on the server-side.

You seem to be asking for something like @Html.HiddenFor(m => m.Model), and that is not possible. Sorry

One thing to keep in mind, if you have tons of hidden fields, you may be sending more data to the view than you really need. Consider employing view models

For anyone else who looks at this you can do a @Html.EditorForModel() in a hidden div. You'd also have to use @Html.EditorFor(model => model.ObjectProperty) for each object property of the model.

<div hidden="hidden">
  @Html.EditorForModel()
  @Html.EditorFor(model => model.ObjectProperty)
  @Html.EditorFor(model => model.ListOfObjectsProperty)
</div>
sacha

The entire model will be posted if you are using a FORM element. Your elements using the Model obviously need to be inside the form element

You can also POST the form yourself say by using JQuery

See this other stack issue for that : jQuery AJAX submit form

Have a close look at the anwser by "Alfrekjv"

This is already built in. Consider this model:

public class MyModel
{
    public string PropertyA { get; set; }
    public string parameter { get; set; }
}

and now consider this action:

[HttpPost]
public ActionResult PostSomeData(MyModel model)
{
}

MVC will leverage the FormCollection and fill in the MyModel class where it can. If you don't have the PropertyA in the form then it will be null. But since you have an input for the parameter property it will be filled in.

You can check only the properties you want:

if (this.ModelState.IsValidField("Name"))
{
     // .....
}

instead of:

if (this.ModelState.IsValid)
{
     // .....
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!