javascriptc#asp.net-mvcrazorhtml.actionlink

How can I get an HTML tag’s value to send an HTML.Action()


I have these lines of code:

<span 
  class="close-modal"
  onclick="@Html.Action("SaveNotes", "CallCenter", new { activityId = item.callIdKey, noteText = "test1" })">
  &times;
</span>
&nbsp;
Notes: <br />
<textarea name="paragraph_text" rows="5" style="width:90%">
  @item.NoteText 
</textarea>

I would like to replace test1 from the noteText route variable and instead change it to whatever the value in the <textarea> tag is.

Is there an elegant way of doing this without writing a giant block of jQuery code?


Solution

  • A @gunr2171 notes in the comments, the only way to dynamically update a link once it's been rendered to the browser is via some form of client-side scripting, typically JavaScript. In your case, I'd recommend doing something like this:

    <span 
      class="close-modal" 
      data-href-template="@Url.Action("SaveNotes", "CallCenter", new {activityId = item.callIdKey, noteText="{note}"})"
      >
      &times;
    </span>
    

    Note: As @HBlackorby notes in his answer, you shouldn't be using @Html.Action() here; I assume you meant @Url.Action().

    This way, your JavaScript has a template (data-href-template) that it can work against with a clearly defined token ({note}) to replace, instead of needing to parse the URL in order to identify where the previously replaced text is. Otherwise, you potentially end up in a scenario where you type e.g. CallCenter into your <textarea /> and it's now an ambiguous reference that you can't just blindly replace. Or, worse, you type 'a' and it's really ambiguous.

    If you are already using jQuery on your site, the actual replacement might be done using something along the lines of:

    $(document).ready(function () {
      $('span.close-modal').click(function() {
        var noteInput    = $('textarea[name="paragraph_text"]');
        var encodedNote  = encodeURI(noteInput.text());
        var template     = $(this).data("href-template");
        var targetUrl    = template.replace("{note}", encodedNote);
        window.location.href = targetUrl;
      });
    });
    
    

    You can also do this without jQuery, obviously—and should if you're not already depending on it. The point is to illustrate that this doesn't necessarily need to be a "giant block of jQuery code". In fact, this could be done in just a few lines—and probably should be. I deliberately broke it out into multiple steps and variables for the sake of readability.