[英]Pass viewbag to partial view from action controller
我有一个部分视图的mvc视图。控制器中有一个ActionResult方法,它将返回一个PartialView。 所以,我需要将ViewRag数据从ActionResult方法传递给Partial View。
这是我的控制器
public class PropertyController : BaseController
{
public ActionResult Index()
{
return View();
}
public ActionResult Step1()
{
ViewBag.Hello = "Hello";
return PartialView();
}
}
在Index.cshtml视图中
@Html.Partial("Step1")
Step1.cshtml局部视图
@ViewBag.Hello
但这不起作用。 那么,从viewbag获取数据的正确方法是什么。 我想我正在遵循错误的方法。 请指导我。
你可以按照下面的说法使用它:
在您的视图中:
@Html.Partial("[ViewName]", (string)ViewBag.Message)
而你的部分观点:
@model String
<b>@Model</b>
如上所示,ViewBag.Message将传递给局部视图。 在局部视图中,您可以将其用作@Model 。
注意:这里ViewBag.Message的类型是字符串 。 你可以传递任何类型。
如果您不必使用ViewBag,则可以使用TempData。 TempData是整个执行链共享的。
public class PropertyController : BaseController
{
public ActionResult Index()
{
return View();
}
public ActionResult Step1()
{
TempData["Hello"] = "Hello";
return PartialView();
}
}
在Index.cshtml视图中
@Html.Partial("Step1")
Step1.cshtml局部视图
@TempData["Hello"]
老问题,但如果有人在这里找到这个问题的解决方案..
您可以使用viewdatadictionary将viewbag值传递给partial。
在你看来:
@Html.Partial("_Partial", "", new ViewDataDictionary { { "permalink", ViewBag.Permalink } })
在部分视图中使用它像这样:
ViewData["permalink"]
您可以尝试此操作,以便将ViewBag传递给操作中的部分视图:
你的控制器:
public class PropertyController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Step1()
{
ViewBag.Hello = "Hello";
return PartialView("_Partial1", ViewBag.Hello);
}
}
你的观点(Index.cshtml):
@Html.Action("Step1")
您的部分视图(_Partial1.cshtml):
@ViewBag.Hello
return PartialView("partialviewname", obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.