Sinoy Devassy
Sinoy Devassy

Reputation: 574

How can i make reusable partialview in asp.net MVC 3

I want to make a partialview with 2 dropdownlists. DDL data have to generate from db. I am new in MVC. What will be the proper way to make this Partialview?

Thanks

Upvotes: 2

Views: 3700

Answers (2)

Jakub Konecki
Jakub Konecki

Reputation: 46008

From my experience it's better to create action and call RenderAction() passing relevant parameters than using RenderPartial(). The reason is that you need to pass a fully populated model to RenderPartial and that means you have to duplicate the code for populating this model in all the controllers that use this 'partial view'.

I found it much cleaner to create a separate action that can receive a number of parameters (ie. id of the object) and than perform all the required steps to populate the model (ie. load the object from database). You can mark that new action with ChildActionOnly attribute so it cannot be called directly.

Upvotes: 2

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10512

(Assuming you're using Visual Studio)

Under Views folder in your project find a folder named "Shared" (or create it if doesn't exist). Right-click this folder, select "Add->View". In the dialog "Add View" specify view name, model type (if you wish) and set the checkbox "Create as a partial view". Model type should probably be a new model class with two List<string> elements.

Anywhere you need to use this view, include the markup

@Html.RenderPartial("YourPartialViewName", YourModel);

where YourModel has the same type as a model specified in partial view declaration.

Upvotes: 4

Related Questions