Asp.net mvc 3 MVC3 Razor-如何将数据从控制器传递到视图并返回到控制器

Asp.net mvc 3 MVC3 Razor-如何将数据从控制器传递到视图并返回到控制器,asp.net-mvc-3,razor,Asp.net Mvc 3,Razor,我有一个视图,其中所有内容都将由用户填充,但与父实体相关。我使用ViewBag将该Id传递给我的视图,但我不知道如何将其返回到控制器中的post操作。我尝试过隐藏表单字段,但它没有显示在帖子中,或者我不知道如何抓取它。。。 控制器: public ActionResult AddCar(int id) { ViewBag.Id = id; return View(); } 查看(已尝试): 如何在控制器中检索post操作中的值?还是有更好的/不同的方法来解决? 谢谢试着这样做: @using

我有一个视图,其中所有内容都将由用户填充,但与父实体相关。我使用ViewBag将该Id传递给我的视图,但我不知道如何将其返回到控制器中的post操作。我尝试过隐藏表单字段,但它没有显示在帖子中,或者我不知道如何抓取它。。。 控制器:

public ActionResult AddCar(int id)
{
ViewBag.Id = id;
return View();
}
查看(已尝试):

如何在控制器中检索post操作中的值?还是有更好的/不同的方法来解决? 谢谢

试着这样做:

@using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = ViewBag.Id }))
{
    ...
}

为post创建ViewModel,如下所示

public class Post
{
   int id {get;set;}
   //other properties
}
并在控制器操作中发送一个post对象

public ActionResult AddCar(int id)
{
 Post post = new Post();
 post.Id = id;
return View(post);
}
您的视图应该使用Post类作为模型

@model namespace.Post
@using (Html.BeginForm("AddReturn", "DealerAdmin", FormMethod.Post)
    {
      @Html.HiddenFor(model => model.Id)
    }
期望结果的控制器操作应该有一个post对象作为输入参数

public ActionResult AddReturn(Post post)
{
 //your code
}
有办法
1.如果只有一个值要发送到控制器,则发送带有查询字符串的值
2.如果要从视图中收集多个字段,可以使用formcollection
样本::

鉴于

<form method="post" action="method1" enctype="now i dont remeber the value of this option" >

@html.hidden("id")
.....

<input type="submit" value"Send"/>
</form>

[httpPost]
public actionresult method1(fromcollection collection)
{
 int id = collection.get("id");
 ....
 //and other field to collect
}

@html.hidden(“id”)
.....
[httpPost]
公共操作结果方法1(来自集合)
{
int id=collection.get(“id”);
....
//和其他要收集的字段
}

隐藏字段应该可以工作。问题是您的控制器没有接受它

您可以使用ViewModel来实现这一点。或者,在操作中使用以下代码:

id = Request.Form["id"]

非常感谢。如何在我的控制器中检索我的post操作中的值?您可以让控制器操作采用具有
Id
属性的视图模型。默认模型绑定器将自动填充此属性。感谢您的回复。我用了申请表,罗比·肖写的。
<form method="post" action="method1" enctype="now i dont remeber the value of this option" >

@html.hidden("id")
.....

<input type="submit" value"Send"/>
</form>

[httpPost]
public actionresult method1(fromcollection collection)
{
 int id = collection.get("id");
 ....
 //and other field to collect
}
id = Request.Form["id"]