Note that there are some explanatory texts on larger screens.

plurals
  1. POPass JavaScript to a Partial View
    primarykey
    data
    text
    <p>I'm trying to come up with a generic solution to buttons triggering JavaScript functions in ASP.NET MVC 3. To that end I created a C# ToolButton class and a partial view with that same name as follows:</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;ToolButton&gt;" %&gt; &lt;%@ Import Namespace="Models.Shared" %&gt; &lt;script src="&lt;%= Url.Content("~/Scripts/Utility/toolbutton.js") %&gt;" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function () { $('&lt;%: String.Format("#{0}", Model.Id) %&gt;').toolbutton({ 'onClick': function () { alert('xyz'); } }); }); &lt;/script&gt; &lt;div id="&lt;%: Model.Id %&gt;" class="tool-button"&gt;&lt;/div&gt; </code></pre> <p>Noticed the onClick handler? I'll come to that in a jiffy. toolbutton.js is a custom jQuery extension and handles all the events. The idea now is to have, say, an IEnumerable with buttons that trigger different (purely JavaScript driven) events, like so:</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;IEnumerable&lt;ToolButton&gt;&gt;" %&gt; &lt;%@ Import Namespace="Models.Shared" %&gt; &lt;div class="tool-panel"&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;% foreach (var toolButton in Model) { %&gt; &lt;td&gt;&lt;% Html.RenderPartial("ToolButton", toolButton); %&gt;&lt;/td&gt; &lt;% } %&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>The problem now is, that I can't figure out how to pass the event handler to a particular instance of ToolButton. I'd like to execute a custom JavaScript handler for any single button in the enumeration, for example one button clears a textarea and another button fills that same textarea with some pre-formatted text - when that button is clicked, i.e. I need to pass in a handler for onClick that gets set when that instance of ToolButton is initalized (typically when ToolButton.ascx is partially rendered).</p> <p>Is there any way of passing JavaScript to a partial view?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload