如何将参数传递给ASP.NET MVC中的局部视图?

时间:2011-07-01 14:48:38

标签: asp.net-mvc model-view-controller asp.net-mvc-3 controller partial-views

假设我有这个局部视图:

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

可通过仅限子项的操作访问:

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

}

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

@Html.RenderPartial("FullName")

换句话说,我希望能够将firstName和lastName从视图传递到局部视图。我该怎么办?

6 个答案:

答案 0 :(得分:76)

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

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

这样:

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

答案 1 :(得分:72)

如果你想使用ViewData,这是另一种方法:

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

并检索传入的值:

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

答案 2 :(得分:24)

您需要创建一个视图模型。这样的事情应该......

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

答案 3 :(得分:13)

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

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

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

答案 4 :(得分:3)

以下是 dotnet 1.0.1

为我工作

<强> ./ ourView.cshtml

<p>

<强> ./_ ourPartial.cshtml

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

答案 5 :(得分:-2)

只需:

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