Asp.net-Mvc

如何將參數傳遞給 ASP.NET MVC 中的局部視圖?

  • July 1, 2011

假設我有這個部分觀點:

Your name is <strong>@firstName @lastName</strong>

可以通過僅限兒童的操作訪問,例如:

[ChildActionOnly]
public ActionResult FullName(string firstName, string lastName)
{

}

我想在另一個視圖中使用這個局部視圖:

@Html.RenderPartial("FullName")

換句話說,我希望能夠將 firstName 和 lastName 從視圖傳遞到部分視圖。我該怎麼做?

使用這個重載(RenderPartialExtensions.RenderPartial在 MSDN 上):

public static void RenderPartial(
   this HtmlHelper htmlHelper,
   string partialViewName,
   Object model
)

所以:

@{Html.RenderPartial(
   "FullName",
   new { firstName = model.FirstName, lastName = model.LastName});
}

如果您想使用 ViewData,這是另一種方法:

@Html.Partial("~/PathToYourView.cshtml", null, new ViewDataDictionary { { "VariableName", "some value" } })

並檢索傳入的值:

@{
   string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? this.ViewData["VariableName"].ToString() : string.Empty;
}

引用自:https://stackoverflow.com/questions/6549541