在控制器局部视图中访问ViewBag

时间:2018-10-18 11:35:33

标签: c# asp.net-mvc

如何在控制器局部视图中传递View Bag。

下面是我在局部视图中的actionResult:

public ActionResult _Container()
{
   var ListContainerType = db.tblM_ContainerType.Where(a => a.IsActive == true).Select(a => new { a.Id, text = a.Code + " - " + a.Name }).ToList();
   List<SelectListItem> slContainerType = new SelectList(ListContainerType, "Id", "text").ToList();
   ViewBag.ContainerTypeId = slContainerType;

   List<SelectListItem> slContainerSize = new SelectList(db.tblM_ContainerSize.Where(a => a.IsActive == true), "Id", "Detail").ToList();
   ViewBag.ContainerSizeId = slContainerSize;

   return View();
}

在部分视图中访问时有错误称呼:

<select type="text" name="ddlTypeContainer" id="ddlTypeContainer" class="form-control" required>
    <option value="">&nbsp;</option>
    @foreach (var item in ViewBag.ContainerTypeId)
    {
        <option value="@item.Value">@item.Text</option>
    }
</select>

我如何这样称呼局部视图:

 @Html.Partial("_Container")

1 个答案:

答案 0 :(得分:0)

如果您的意思是如何从任何视图调用局部视图,我建议您使用此简单解决方案

首先,如果您的项目中没有共享文件夹,则可以在视图文件夹中轻松创建它们,然后将其命名为共享并复制过去,则应在项目的共享文件夹中建立或放置部分视图您的局部视图(您的.Cshtml文件),然后使用:

df_x <- data.frame(VAR0=c("A","P","C","D","Z"), stringsAsFactors = F)

df_y <- data.frame(VAR1=c("A","B","C","D","E"),
                   VAR2=c("A","F","T","D","Z"),
                   VAR3=c("YES", "YES", "NO", "MAYBE", "YES"),
                   stringsAsFactors = F)

require(dplyr)
# LEFT JOIN TWICE TO MEET BOTH CONDITIONS
lj_1 <- left_join(df_x, df_y, by=c("VAR0" = "VAR1"))
lj_2 <- left_join(df_x, df_y, by=c("VAR0" = "VAR2"))

# THEN REPLACE NAs FROM FIRST LEFT JOIN WITH VALUE FROM SECOND LEFT JOIN
ifelse(lj_1$VAR3 %in% NA, lj_2$VAR3, lj_1$VAR3)
# [1] "YES"   NA      "NO"    "MAYBE" "YES"

真心希望这对你兄弟有帮助