fearofawhackplanet
fearofawhackplanet

Reputation: 53456

Passing additional data value to strongly typed partial views in ASP.NET MVC

I have an OrderForm domain class, which has property subclasses, something like:

interface IOrderForm
{
    int OrderId { get; }

    ICustomerDetails CustomerDetails { get; set; }
    IDeliveryDetails DeliveryDetails{ get; set; }
    IPaymentsDetails PaymentsDetails { get; set; }
    IOrderDetails OrderDetails { get; set; } 
}

My "Details" view is strongly typed inheriting from IOrderForm. I then have a strongly type partial for rendering each section:

<div id="CustomerDetails">
    <% Html.RenderPartial("CustomerDetails", Model.CustomerDetails); %>
</div>

<div id="DeliveryDetails">
    <% Html.RenderPartial("DeliveryDetails", Model.DeliveryDetails); %>
</div>

... etc

This works ok up to this point, but I'm trying to add some nice ajax bits for updating some parts of the order form, and I've realised that each of my partial views also needs access to the IOrderForm.OrderId.

Whats the easiest way to give my partials access to this value?

Upvotes: 1

Views: 1889

Answers (4)

Muhammad Soliman
Muhammad Soliman

Reputation: 23876

Simply depend on a Model for RenderPartial, simply pass your model through.

<% Html.RenderPartial("~/controls/users.ascx", modelGoesHere); %>

then inside the partial view itself, normally you could do the following:

<%= Model.VariableName %>

Upvotes: 0

moi_meme
moi_meme

Reputation: 9328

you can get the value from your Route using something like

this.ViewContext.RouteData.GetRequiredString["OrderId"]

Or your add it to your viewData and reuse pass it to your partialView

TempData is also a pretty simple way...

Upvotes: 2

Robert Harvey
Robert Harvey

Reputation: 180948

There is an overload for RenderPartial that accepts both a Model object and a ViewData dictionary, so potentially you could just set a ViewData value, and pass the ViewData object to the partial.

Another option is to include an Order Id member in your partial ViewModel, and copy the Order Id to it.

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86902

You would have to change your code a bit but you could do this

<div id="CustomerDetails"> 
    <% Html.RenderPartial("CustomerDetails", new {OrderID = Model.OrderID,  CustomerDetails = Model.CustomerDetails}); %> 
</div> 

<div id="DeliveryDetails"> 
    <% Html.RenderPartial("DeliveryDetails", new {OrderID = Model.OrderID, DeliveryDetails = Model.DeliveryDetails); %> 
</div> 

Or you could assign the OrderID to tempData in the Action

TempData("OrderId") = your orderIDValue

Upvotes: 2

Related Questions