Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 378
Saeed Neamati Avatar asked Jul 01 '11 14:07

Saeed Neamati


People also ask

How do I pass ViewData in partial view?

You're almost there, just call it like this: Html. RenderPartial( "ProductImageForm", image, new ViewDataDictionary { { "index", index } } ); Note that this will override the default ViewData that all your other Views have by default.


2 Answers

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; } 
like image 111
Garry English Avatar answered Sep 25 '22 01:09

Garry English


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}); } 
like image 29
David Wick Avatar answered Sep 27 '22 01:09

David Wick