如何在 ASP.NET MVC 中向部分视图传递参数?

假设我有这样的部分观点:

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

只有儿童才能通过以下行动获得:

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


}

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

@Html.RenderPartial("FullName")

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

180635 次浏览

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

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.

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

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

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>

Just:

@Html.Partial("PartialName", Model);
@{
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

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