title: ASP.NET selecting table row on click using jquery
body: <p>I have a table in ASP.NET. I have implemented the functionality to select any single row by using a select link at the end of the row.</p>
  
  <p><a href="https://i.stack.imgur.com/Pj7r6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pj7r6.png" alt="enter image description here"></a></p>
  
  <h2>Selecting a row by View and Controller:</h2>
  
  Views/Vehicle/Index.cshtml
  
  <p>I am setting a value in the top of the view:</p>
  
  <pre><code>@{
      bool itemSelected = false;
  }
  </code></pre>
  
  <p>and then the following comes inside the creation of rows:</p>
  
  <pre><code>@foreach (var item in Model)
  {
      string selectedRow = "";
      if (item.VehicleID == (int?)ViewData["VehicleID"])
      {
          selectedRow = "success";
          itemSelected = true;
      }
          &lt;tr class="@selectedRow"&gt;
              &lt;td&gt;
                  @Html.DisplayFor(modelItem =&gt; item.Alias)
              &lt;/td&gt;
              &lt;td&gt;
                  @Html.DisplayFor(modelItem =&gt; item.Vehicle_Type)
              &lt;/td&gt;
  
              ...
  
          &lt;/tr&gt;
  }
  </code></pre>
  
  <p>and at the very buttom this snippet:</p>
  
  <pre><code>@if (itemSelected)
  {
      int elementID = (int)ViewData["VehicleID"];
      var item = Model.FirstOrDefault(v =&gt; v.VehicleID == elementID);
  
      if (item != null)
      {
          @Html.Partial("PartialVehicleDetails", item)
      }
  }
  </code></pre>
  
  <p>All of this is run when clicking the following link found in my table at the very end as seen on the screenshot.</p>
  
  <pre><code>&lt;a asp-action="Index" asp-route-id="@item.VehicleID" asp-route-sortOrder="@ViewData["CurrentSort"]"&gt;Select&lt;/a&gt; |
  </code></pre>
  
  Controllers/VehicleController.cs
  
  <pre><code>public async Task&lt;IActionResult&gt; Index(int? id)
  {
      if(id != null)
      {
          ViewData["VehicleID"] = id.Value;
      }
  }
  </code></pre>
  
  <p>What is done above is taking all the properties of a vehicle and showing them if the row is selected in a PartialView called <code>PartialVehicleDetails.cshtml</code> below the table.</p>
  
  <p>Now I'm wondering if it is possible to use jQuery to select the row similar to what I'm already doing, however without using the above shown link. I have already been able to create a jQuery function that reacts to me clicking a row, but I don't know if it is possible to connect the two together.</p>
  
  <pre><code>$("table tbody tr").click(function () {
      //$(this).addClass("success") //this should add the color to clicked row (but not remove from the other rows).
  });
  </code></pre>
  
  <h1>Question in short</h1>
  
  <p>Is it possible to do the stuff done in above view and controller using jQuery when a row is selected/clicked?</p>
  
  <p>Thanks!</p>