Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MVC-使用C#用Json操作结果填充ViewBag_C#_Asp.net Mvc_Viewbag_Actionresult - Fatal编程技术网

MVC-使用C#用Json操作结果填充ViewBag

MVC-使用C#用Json操作结果填充ViewBag,c#,asp.net-mvc,viewbag,actionresult,C#,Asp.net Mvc,Viewbag,Actionresult,我有一个MVC网站,后面有C代码。我使用的是ActionResult,它返回Json 我正试图在ViewBag中放入一些内容,但它似乎不起作用 代码如下所示- public ActionResult GetStuff(string id) { ViewBag.Id = id; stuff = new StuffFromDatabase(id); return this.Json(stuff , JsonRequestBehavi

我有一个MVC网站,后面有C代码。我使用的是ActionResult,它返回Json

我正试图在ViewBag中放入一些内容,但它似乎不起作用

代码如下所示-

    public ActionResult GetStuff(string id)
    {
        ViewBag.Id = id;

        stuff = new StuffFromDatabase(id);

        return this.Json(stuff , JsonRequestBehavior.AllowGet);
    }
“id”不会出现在ViewBag.id中

我可以这样把身份证放在取景袋里吗?如果没有任何关于我应该怎么做的建议?
谢谢

您试图在Json结果中设置
ViewBag.Id
<代码>视图包在视图中使用,而不是在
Json
中使用

已添加

正如我从评论中看到的,如果你试图在javascript中使用它,你可以做这样的事情。试试这个:

return this.Json(new {stuff, id} , JsonRequestBehavior.AllowGet);

然后您可以使用javascript访问此数据。

ViewBag仅在服务器端可用。您正在将一个json字符串发送回浏览器,可能浏览器随后会对其进行处理。您必须在json响应中发送id,如下所示:

return this.Json(new { Id = id, Data = stuff }, JsonRequestBehaviour.AllowGet);

另一种解决方案是:如果希望在返回json结果的post操作后访问“id”属性,则可以返回包含所有必需数据的复杂对象:

public ActionResult GetStuff(string id)  
{  
    ViewBag.Id = id;  

    stuff = new StuffFromDatabase(id);  

    return this.Json(new { stuff = stuff, id = id } , JsonRequestBehavior.AllowGet);  
} 
之后,在json返回值中,您可以访问以下示例中的所有属性:

$.post(action, function(returnedJson) {
   var id = returnedJson.id;
   var stuff = returnedJson.stuff;
});

你是如何在视图中使用ViewBag的?实际上,我只是希望在发布帖子时,我在ViewBag中输入的值可以在我的C代码中访问。比如-var currentId=ViewBag.IdI我很困惑。。因为您已经将id作为参数传递了?id不在我在Json对象中返回的“东西”中。我想发布到C#代码隐藏,比如[HttpPost]公共操作结果GotStuf(FormCollection FormCollection){var currentId=ViewBag.Id;},所以您想在视图中设置ViewBag.Id。.我实际上需要在C#POST代码中访问它。我想将id存储在ViewBag中。id然后在发布帖子时引用ViewBag.id。我将使用此RobyContent(以及其他一些代码)谢谢!