MVC sends data from View to Controller

I am new to MVC 3.

I know how to send a strongly typed object from a controller to a view. Now I have a view that contains a table / form consisting of this data.

The user can change this data while they are in this view (html page).

When they click Save, how do I send data from the view back to the controller so that I can update my database.

Am I overloading a controller method so that it accepts a model type parameter? Could you provide some source code.

(Please do not show the code of the stored data in the database, I know how to do it).

Thanks for helping me.

I would also prefer to use @Html.BeginForm()

+6
source share
2 answers

I like to create an action method for my posts. So let's say you have a UserViewModel:

 public class UserViewModel { public int Id { get; set; } public string Name { get; set; } } 

Then UserController:

 public class UserController { [HttpGet] public ActionResult Edit(int id) { // Create your UserViewModel with the passed in Id. Get stuff from the db, etc... var userViewModel = new UserViewModel(); // ... return View(userViewModel); } [HttpPost] public ActionResult Edit(UserViewModel userViewModel) { // This is the post method. MVC will bind the data from your // view form and put that data in the UserViewModel that is sent // to this method. // Validate the data and save to the database. // Redirect to where the user needs to be. } } 

I assume you already have a form. You want to make sure the form submits data to the correct action method. In my example, you create the form as follows:

 @model UserViewModel @using (Html.BeginForm("Edit", "User", FormMethod.Post)) { @Html.TextBoxFor(m => m.Name) @Html.HiddenFor(m => m.Id) } 

The key to all this is the binding of the model that MVC performs. Use HTML helpers like the Html.TextBoxFor I used. In addition, you will notice the top line of view code that I added. @model tells you that you will send it a UserViewModel. Let the engine work for you.

Edit: Nice call, it's all in Notepad, forgot HiddenFor for Id!

+9
source

In MVC, the act of scraping data from a POST or GET HttpRequests is called model binding - there are many SO questions related to this.

Out of the box, MVC will bind your Get and Post variables based on convention, for example. a form field named "FormName" will be bound to a parameter on your controller with the same name.

Model binding also works for objects - MVC will instantiate an object for your controller and set properties with the same name as your form.

+1
source

Source: https://habr.com/ru/post/924094/


All Articles