Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

Send a parameter to a partial view

I'm new in .NET development and need some help.

I need to display stars in function of a rating. This display will appear in most of my pages into the code.

So, I think that the best way to handle this is using a partial view.

After a few researches, I've found something that should enable me to send this parameter to the partial view.

For example, by calling the partial view like that

 @Html.Partial("~/Views/Search/_SearchPartial.vbhtml", model.contact.rating)

But, I don't know how to catch this parameter inside the partial view. Furthermore, the context won't ever be the same. Sometimes, the stars that I'll have to display will be from another rating. Does it change something?

Upvotes: 2

Views: 2321

Answers (3)

Yorgo
Yorgo

Reputation: 2678

using editor-templates or display-templates more efficient for that situation. For using templates

  1. Create that folders:

    Views / Shared / DisplayTemplates

  2. Create an view inside DisplayTemplates folder. Call it Rating.cshtml and paste that code:

    @model int
    
    <div><p>Current rating: @Model</p></div>
    
  3. Call this template in your view instead of @Html.Partial:

    @Html.DisplayFor(model=>model.contact.rating, "Rating")
    

Upvotes: 1

Balazs Tihanyi
Balazs Tihanyi

Reputation: 6719

The rating value will be the partial view's Model object (as an integer or double), use it like you would in a normal view.

Upvotes: 1

Kasper Holdum
Kasper Holdum

Reputation: 13353

When you pass the rating to the partial view you can access it via the Model object inside the partial view

<div>
<p>Current rating: @Model</p>
<div>

For the view to know the type of the model it is dealing with you need to specify the type at the top of your partial view:

@model MyNamespace.MovieRating

<div>
 <p>Current rating: @Model</p>
<div>

All this assumes that the rating object will always be of the same type. If you have different rating objects, then you will either need to parse them into a single type, or create one view for every type of rating object.

Upvotes: 1

Related Questions