问题描述
我很新的MVC 3。
我知道如何从一个控制器发出一个强类型的对象视图。我现在已经是它包含一个表/表单其中包括该数据的视图。
I know how to send a strongly typed object from a Controller to a View. What I have now, is a View which contains a table/form which consists of that data.
,而他们是在该视图(HTML页面),用户可以更改这些数据。
The user can change that data whilst they're are in that View (html page).
当他们点击保存,我怎么从视图发送数据到控制器,这样我可以更新我的数据库。
When they click on "Save", how do I send the data from the View back to the Controller so that I can update my database.
我是否过载控制方法,以便它接受模型类型的参数?能否请您提供一些源$ C $ C。
Do I overload the Controller method so that it accepts a parameter of the model type? Can you please provide some source code.
(请不要持续显示数据到数据库code,我知道该怎么做一部分)。
(Please do not show code of persisting data to a database, I know how to do that part).
非常感谢你对我的帮助。
Thank you very much for helping me.
我也要用preFER @ Html.BeginForm()
I would also prefer using @Html.BeginForm()
推荐答案
我喜欢创造我的岗位数据所做的操作方法。因此,让我们假设你有一个UserViewModel:
I like creating an action method made for my post data. So let's say you have a UserViewModel:
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
然后,UserController的:
Then a 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's 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'm assuming you have a form in your view already. You'll want to make sure that the form posts the data to the correct action method. In my example, you'd create the form like so:
@model UserViewModel
@using (Html.BeginForm("Edit", "User", FormMethod.Post))
{
@Html.TextBoxFor(m => m.Name)
@Html.HiddenFor(m => m.Id)
}
这一切的关键是模型绑定MVC一样。利用HTML佣工,像我用的Html.TextBoxFor。此外,你会发现视图code我加的顶线。该@model告诉你会发送一个UserViewModel的看法。让引擎为你做的工作。
The key to all this is the model binding that MVC does. Make use of the HTML helpers, like the Html.TextBoxFor I used. Also, you'll notice the top line of the view code I added. The @model tells the view you'll be sending it a UserViewModel. Let the engine do work for you.
编辑:良好的通话,这样做都在记事本,忘了ID的HiddenFor
Good call, did that all in Notepad, forgot a HiddenFor for the Id!
这篇关于MVC从View将数据发送到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!