Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18421

MVC 4 Razor user control

I want to create something like a user control in my MVC 4 project. I have followed the instructions in this article so i have added the App_Code folder(it was not initially there) in the project. Inside i have put a file

VDRazorHelpers.cshtml

Inside that file i have my code which is actually a static html table(i would add dynamic values later):

@helper PropertySummary(){
    <tr>
        <td width="210" align="center" colspan="2">
            <img src="http://www.mysite.com/images/BG1.JPG" width="210" height="140" />
        </td>
    </tr>

}

Then in my view i try to access that helper writing:

@VDRazorHelpers.PropertySummary

but this doesn't seem to be available.

I know the article i mentioned is for MVC3. Has it change? What would be the proper way of having custom reusable html parts in MVC4?

Here is the screenshot of the intellisense:

enter image description here

Upvotes: 0

Views: 10016

Answers (2)

asymptoticFault
asymptoticFault

Reputation: 4529

Partial Views are the closest to an analogue of a Web Forms User Control in MVC. They encapsulate HTML that can be reused on other views or returned directly from action methods, which is handy for AJAX calls that need to fetch some HTML. Big difference in MVC is that the Partial Views don't have the ViewState of a User Control in Web Forms, nor does anything, it's gone, and good riddance as far as I'm concerned. HTML Helpers could also be considered close to User Controls however they are completely based in code and generate HTML whereas Partial Views are the markup.

Upvotes: 1

Richard
Richard

Reputation: 22036

I would be more inclined to use a partial view which you could place in the shared views folder then call passing the model you wish to render with that view:

@Html.Partial("propertySummary", property)

Just a thought

Upvotes: 6

Related Questions