We need to create multiple partial views of the same type, but this partial view has a javascript function. How can I avoid the definition of this function on each partial view? We don't want to define this function in another place.
2 Answers
Move the definition of the function out of the partial and into a global\external JavaScript file:
External JS
function foo () {
/* ... code ... */
}
Partial
foo();
or (depending on how foo is defined you may want to create an instance of foo):
var bar = new foo();
I would highly recommend altering the solution to allow an extern javascript referece. If this just cannot be done, then the following might work. First I'll assume you're doing something like:
/Views/Shared/MyModelPartial1.cs/
@model MyModel
<script type="text/javascript">
var a = "@Model.SomeStringProperty";
var b = @Model.SomeNumberProperty;
</script>
<span>Some Html!</span>
/Views/Shared/MyModelPartial2.cs/
@model MyModel
<script type="text/javascript">
var a = "@Model.SomeStringProperty";
var b = @Model.SomeNumberProperty;
</script>
<div>Different Html Than 1</div>
If you're trying to share this Javascript between two Partials, then create another partial view that might look something like:
/Views/Shared/MyModelJavascript.cs/
@model MyModel
<script type="text/javascript">
var a = "@Model.SomeStringProperty";
var b = @Model.SomeNumberProperty;
</script>
/Views/Shared/MyModelPartial1.cs/
@model MyModel
@Html.Partial("MyModelJavascript", Model)
<span>Some Html!</span>
/Views/Shared/MyModelPartial2.cs/
@model MyModel
@Html.Partial("MyModelJavascript", Model)
<div>Different Html Than 1</div>