1

I've got a couple large sections of razor code that similar enough that they should be coming from a reusable source.

What I want to do is make a cshtml file that can be called from another cshtml file, except I should be able to send it some c# input variables to help generate the thing. I don't know what the lingo for this sort of pattern is in the MVC world.

I know how to make HTML helpers, and I certainly can make an HTML helper as an alternative.

1
  • 2
    HtmlHelper, EditorTemplates, PartialViews or ChildActions (that return a partial) are all options. It really depends on on your circumstances. Commented Feb 21, 2015 at 5:32

1 Answer 1

5

You can keep one cshtml file and then call it from another cshtml by using

@Html.RenderPartial("ReusableView", DataParameters)

Assuming you're using MVC. In my experience I've only passed it View Models but the docs say it can be anything. As for pulling the data out from the parameters...

@model ViewModelName

is how I've always done it...

and if you use the view more than once on a page you'll want to make sure there's no javascript in it because the javascript will show up on your main page once for every time you call the partial view. But I think this sounds like what you're asking for

Sign up to request clarification or add additional context in comments.

2 Comments

I'll give it a try, thank you daniel! I Did see a renderPartial call somewhere before but I forgot about that. Useful suggestion.
From Razor for this to work I need to call it between curly braces, like so: @Html.RenderPartial("ReusableView", DataParameters)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.