我对MVC 3很新.
我知道如何将强类型对象从Controller发送到View.我现在拥有的是一个包含由该数据组成的表/表单的视图.
用户可以在该视图(html页面)中更改该数据.
当他们点击"保存"时,如何将数据从View发送回Controller,以便我可以更新我的数据库.
我是否重载Controller方法,以便它接受模型类型的参数?你能提供一些源代码吗?
(请不要向数据库显示持久数据的代码,我知道如何做这部分).
非常感谢你帮助我.
我也更喜欢使用 @Html.BeginForm()
我喜欢为我的帖子数据创建一个动作方法.所以假设你有一个UserViewModel:
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后是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.
}
}
Run Code Online (Sandbox Code Playgroud)
我假设你已经在你的视图中有一个表单.您需要确保表单将数据发布到正确的操作方法.在我的示例中,您将创建如下表单:
@model UserViewModel
@using (Html.BeginForm("Edit", "User", FormMethod.Post))
{
@Html.TextBoxFor(m => m.Name)
@Html.HiddenFor(m => m.Id)
}
Run Code Online (Sandbox Code Playgroud)
所有这一切的关键是MVC所做的模型绑定.使用HTML帮助程序,比如我使用的Html.TextBoxFor.另外,您会注意到我添加的视图代码的顶行.@model告诉视图你将发送一个UserViewModel.让发动机为你工作.
编辑:好的电话,在记事本中做了所有,忘记了Id的HiddenFor!
| 归档时间: |
|
| 查看次数: |
12263 次 |
| 最近记录: |