MVC3 Razor - 如何从控制器传递数据到视图 - 再返回控制器

3

我有一个视图,用户将填写其中的所有内容,但这些内容都与父实体相关。我使用ViewBag将该ID传递到视图中,但我不知道如何将其返回到控制器中的post操作。我尝试了隐藏表单字段,但它没有在post中显示,或者我不知道如何获取它...

控制器:

public ActionResult AddCar(int id)
{
ViewBag.Id = id;
return View();
}

查看(尝试):

    @using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = carId }))
    {
View (tried):
     @Html.Hidden(carId.ToString())

我该如何在控制器中获取我的post action中的值?或者有更好/不同的方法可以解决这个问题吗? 谢谢

4个回答

9
创建一个帖子的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
}

2
隐藏字段应该能够工作。问题在于您的控制器没有接受它。 您可以使用ViewModel来实现此功能。或者,在您的操作中使用以下代码:
id = Request.Form["id"]

感谢您的回复。我使用了Robby Shaw提供的Request.Form。 - user1166147

0

可以试试这样写:

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

谢谢你。在我的控制器中,我如何检索我的POST操作中的值? - user1166147
您可以让控制器操作使用一个带有“Id”属性的视图模型。默认的模型绑定器将自动填充此属性。 - Darin Dimitrov

0

有几种方法:
1. 如果只需要发送一个值到控制器,可以使用查询字符串发送该值。
2. 如果您想从视图中收集多个字段,可以使用FormCollection。
示例:

public actionresult method1()
{
 int id = //everything you want
 viewbag.id=id;
 ....
 //and other field to collect
}

在视图中

<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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接