01 July 2015

Pass arbitrary parameter to partial view in ASP.NET MVC

I had a chunk of HTML that needed to repeat in a few places, so it made sense to throw it into a partial view. However, each chunk had to have a unique ID for a Bootstrap collapse component. So a parameter needed to be passed in. Some research revealed a rather simple, elegant way in this article. Just pass it as the partial view's model:

@Html.Partial("~/Views/Shared/_TestimonialSubmitPartial", "1")

Then, in the partial view, read it using @Model -- it's the only value passed in, so no dot notation is necessary. Each time I'm using the partial view, I change the value.

In the partial view, I set the data-target of the Bootstrap button to the concatenated ID and also set the collapse div to that same value:
<button class="btn btn-default" 
    data-toggle="collapse" type="button">
    Submit Testimonial
<div class="collapse" id="testimonial-submit-instructions-@Model">

No comments: