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

8

97

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?

Scarron answered 1/7, 2011 at 14:48 Comment(1)
Very closely related question: #1909634Cortie
B
81

Use this overload (RenderPartialExtensions.RenderPartial on MSDN):

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

so:

@{Html.RenderPartial(
    "FullName",
    new { firstName = model.FirstName, lastName = model.LastName});
}
Bicapsular answered 1/7, 2011 at 14:52 Comment(10)
Well, tried that, but I'm getting The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments error. How should I implement the controller method? Should it have input parameters?Scarron
The RenderPartial method returns void, as the views render directly into the output stream, not into a string. I edited my answer to fix this issue.Bicapsular
did you add the {} around the call? it needs to be @{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});} not @Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});Footloose
That did the trick. But it's so messy and dirty. Why should it be wrapped inside another pair of curly braces?Scarron
So you passed parameter like this, how do you access it in partial view?Gaily
You also don't need the brackets. @Html.Partial() is the same as @{Html.RenderPartial();} but much prettier. They have the same overloads as well.Lambertson
How do you access the object? Model.firstName and their like throw an exception that object doesn't have a 'firstName' propertyPoem
As to whether or not you need the brackets, no you don't. However, using the brackets is slightly more optimal because it is written directly to the response stream.Cliquish
@Poem you can access via ViewData... but help keep things tidy by simply creating a model specific to your usage. Use it once and some may consider it a toss up, but use it any more times than that and it's a no-brainer.Cliquish
Can I add Html.RenderPartial as an onclick event for a button?Debor
L
95

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;
}
Lugansk answered 19/8, 2015 at 2:17 Comment(7)
Thanks, your answer did the trick without creating a model for this.Fourdrinier
Out of all the examples, this is the only one that fully worked for me. thanksMuoimuon
This is what i was looking for, no model. thank you :)Bureaucratic
Excellent answer - but with MVC 4 use Html.RenderPartial instead of Html.PartialStonehenge
I had to use new ViewDataDictionary(ViewData) { to get it to work: https://mcmap.net/q/218965/-how-to-use-viewdatadictionary-with-html-partial-in-asp-net-core so: await Html.RenderPartialAsync("~/PathToYourView.cshtml", null, new ViewDataDictionary(ViewData) { { "VariableName", "some value" } } );Cleotildeclepe
@SharpC, It solved the error showing in viedatadictionary but i am unable to get the value in the partial viewYockey
@Cleotildeclepe should be because you were using AspNetCore. ViewDataDictionary is available in System.Web.Mvc and Microsoft.AspNetCore.Mvc.ViewFeatures with different constructors.Chanachance
B
81

Use this overload (RenderPartialExtensions.RenderPartial on MSDN):

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

so:

@{Html.RenderPartial(
    "FullName",
    new { firstName = model.FirstName, lastName = model.LastName});
}
Bicapsular answered 1/7, 2011 at 14:52 Comment(10)
Well, tried that, but I'm getting The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments error. How should I implement the controller method? Should it have input parameters?Scarron
The RenderPartial method returns void, as the views render directly into the output stream, not into a string. I edited my answer to fix this issue.Bicapsular
did you add the {} around the call? it needs to be @{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});} not @Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});Footloose
That did the trick. But it's so messy and dirty. Why should it be wrapped inside another pair of curly braces?Scarron
So you passed parameter like this, how do you access it in partial view?Gaily
You also don't need the brackets. @Html.Partial() is the same as @{Html.RenderPartial();} but much prettier. They have the same overloads as well.Lambertson
How do you access the object? Model.firstName and their like throw an exception that object doesn't have a 'firstName' propertyPoem
As to whether or not you need the brackets, no you don't. However, using the brackets is slightly more optimal because it is written directly to the response stream.Cliquish
@Poem you can access via ViewData... but help keep things tidy by simply creating a model specific to your usage. Use it once and some may consider it a toss up, but use it any more times than that and it's a no-brainer.Cliquish
Can I add Html.RenderPartial as an onclick event for a button?Debor
U
25

You need to create a view model. Something like this should do...

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

}

then from your action result pass the model

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

and you will be able to access @Model.FirstName and @Model.LastName accordingly.

Unreliable answered 1/7, 2011 at 14:57 Comment(0)
F
15

make sure you add {} around Html.RenderPartial, as:

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

not

@Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});
Footloose answered 1/7, 2011 at 16:20 Comment(2)
How does the definition of your Partial View looks? What is the @model declaration? Its anonymous...Hooghly
yes make sure to add { }, i wasted time until i found this articleHann
D
7

Following is working for me on dotnet 1.0.1:

./ourView.cshtml

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

./_ourPartial.cshtml

<h1>@this.ViewData["hi"]</h1>
Dan answered 21/1, 2017 at 1:55 Comment(0)
L
1

Just:

@Html.Partial("PartialName", Model);
Lur answered 4/7, 2017 at 1:2 Comment(0)
A
0
@{
            Html.RenderPartial("_partialViewName", null, new ViewDataDictionary { { "Key", "Value" } });
        } 

in the place you want to show your partial,

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

in the partialview rendered,

To use the valuePassedIn --> @valuePassedIn

Auriol answered 31/8, 2021 at 10:11 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker.Kishke
C
0

I just came across this question, and I have a similar situation

my problem is as follows : I have more than one variable I need to pass to the partial view I created

The solution I have created

@{
await Html.RenderPartialAsync("YourPartialViewName",new { NumberOfProducts = ViewData["NumberOfProducts"], UserName = ViewData["UserName"] });
}

In the above code, I created an anonymous object and sent it to the view and the following code is to explain how to retrieve the data that sent through this object

     <span>
          @Model.UserName
      </span>

     <span>
          @Model.NumberOfProducts
      </span>

hope this helps

Cockatrice answered 24/5, 2022 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.