c# - 查看从 View 到 Controller 的数据

标签 c# asp.net asp.net-mvc viewdata

有没有一种简单的方法可以将对象从我的 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/

相关文章:

c# - MonoTouch - 获取已连接 socket 的列表

c# - 如何创建委托(delegate)来读取匿名类型的属性?

c# - 如何动态获取aspx页面中的所有控件(及其ID)?

asp.net - ASP.Net吞咽404错误

c# - WebAPI 不尊重授权属性的 Jwt token

asp.net-mvc - 使用 DotNetOpenAuth 从 Google 帐户同时获取联系人和日历

c# - 通过一个或多个参数进行过滤

c# - 在 MVVM 中使用 CommandParameter 传递类变量

c# - mvc 2中的图像上传和预览

c# - 通过 AJAX 传递给 Controller ​​的列表为 null