有没有一种简单的方法可以将对象从我的 View 传递到 Controller ?
我尝试了 ViewData["newPerson"]
但没有成功。
Session["newPerson"]
有效,但还有其他更推荐的方法吗?
最佳答案
通常您会收到一个模型作为参数。您必须拥有映射到模型属性的表单字段。
public class PersonViewModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
...
}
那么在你看来:
@model PersonViewModel
@using (Html.BeginForm())
{
<div class="editor-label">@Html.LabelFor( model => model.FirstName )</div>
<div class="editor-field">@Html.EditorFor( model => model.FirstName )</div>
<div class="editor-label">@Html.LabelFor( model => model.LastName )</div>
<div class="editor-field">@Html.EditorFor( model => model.LastName )</div>
...
}
然后在view对应的action中发送和接收model
[HttpGet]
public ActionResult CreatePerson()
{
return View( new Person() );
}
[HttpPost]
public ActionResult CreatePerson( PersonViewModel person )
{
var person = ...create and persist a Person entity based on the view model....
return Redirect("details", new { id = person.id } );
}
关于c# - 查看从 View 到 Controller 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5987010/