2

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.

1
  • 1
    You might also want to consider creating a reusable partial view. Commented Mar 20, 2012 at 2:55

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your response. I've considered this, but I was wondering if are there another way to do it without an external file.
you could execute the code in an immediately executing function that encapsulates the variables of your function in it's own scope...
2

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>

1 Comment

Actually, I have just one partial view. And it could be used in several views. I think I'll take your recommendation to do it with a global/external file indeed.

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.