How to pass parameters to a partial view in ASP.NET MVC?

Saeed Neamati picture Saeed Neamati · Jul 1, 2011 · Viewed 163.2k times · Source

Suppose that I have this partial view:

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

which is accessible through a child only action like:

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

}

And I want to use this partial view inside another view with:

@Html.RenderPartial("FullName")

In other words, I want to be able to pass firstName ans lastName from view to partial view. How should I do that?

Answer

Garry English picture Garry English · Aug 19, 2015

Here is another way to do it if you want to use ViewData:

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

And to retrieve the passed in values:

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