如何将parameter passing给ASP.NET MVC中的部分视图?

假设我有这个部分观点:

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

这是可以通过一个只有儿童的行动,如:

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

我想在另一个视图中使用这个局部视图:

 @Html.RenderPartial("FullName") 

换句话说,我希望能够将firstName ans lastName从视图传递给部分视图。 我该怎么做?

使用此重载( MSDN上的RenderPartialExtensions.RenderPartial ):

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

您需要创build一个视图模型。 这样的事情应该做…

 public class FullNameViewModel { public string FirstName { get; set; } public string LastName { get; set; } public FullNameViewModel() { } public FullNameViewModel(string firstName, string lastName) { this.FirstName = firstName; this.LastName = lastName; } } 

然后从你的行动结果通过模型

 return View("FullName", new FullNameViewModel("John", "Doe")); 

并且您将能够相应地访问@Model.FirstName@Model.LastName

确保你在Html.RenderPartial周围添加{},如下所示:

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

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

以下是在dotnet 1.0.1上为我工作:

./ourView.cshtml

 @Html.Partial( "_ourPartial.cshtml", new ViewDataDictionary(this.Vi‌​ewData) { { "hi", "hello" } } ); 

./_ourPartial.cshtml

 <h1>@this.ViewData["hi"]</h1> 

只是:

 @Html.Partial("PartialName", Model);