2

I know how to render a partial view with jquery.

Now, I am trying to render different content in the same div element each time the user click (using partial views).

I have a method in my home controller

public IActionResult Details(int x)
        {

            Blog A = new Blog() { Id = 1};    
            Blog B = new Blog() { Id = 2};

            if (B.Id == x)
               return PartialView("_blogPartial", B);

      return PartialView("_blogPartial", A);

        }

I am rendering this partial view on click.

$(document).ready(function(){

// For button 1

    $("button1").click(function () {
        $("#partial").load('@Url.Action("Details", new { x = 1})');
    });

 // For button 2
    $("#button2").click(function () {

        $("#partial").load('@Url.Action("Details",new { x=2})');
    });
});

And below are the two buttons .

<button id="button1">BlogA</button>
<button id="button2">BlogB</button>
<div id="partial">

</div>

The problem: If there are 'n' buttons I have to write click function 'n' times for each button. Is there any way that I can pass my button id to the Url.Action() method which will pass it to the Details method.

I need to do something like

$("button").click(function () {
        $("#partial").load('@Url.Action("Details", new { x = buttonid })');
    });
Avan
  • 366
  • 3
  • 17

3 Answers3

1

Just assign click event for the class as I have done below. Here I assign btnClass as class for the each button and make the click event t for the button's class as $(".btnClass").click(function () {});.

Inside this event you can get the button id using the statement as $(this).attr('id').

Your html should like.

<button class="btnClass" id="button1">BlogA</button>
<button class="btnClass" id="button2">BlogB</button>
<div id="partial">

</div>

and Jquery should like as below

  $(".btnClass").click(function () {
       $(this).attr('id');//to get the button id
    });
Jino Shaji
  • 1,097
  • 14
  • 27
  • Had to parse it, to convert into integer and then compare . But worked . Thanks sir. – Avan Sep 19 '17 at 09:37
1

You can use data-attribute and store the id on each the button.

// render this within a loop
<button class="myButton" data-id="2">some text</button>
<button class="myButton" data-id="3">some more text</button>


  $('.myButton').click(function (e) {
       $(e.target).attr('data-id'); the button id to pass to the url
    });
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
1

Rather than and id attribute, its more appropriate to use data- attributes, and then use a class name so you only need one script

<button data-id="1" class="blog" type="button">BlogA</button>
<button data-id="2" class="blog" type="button">BlogB</button>

var url = '@Url.Action("Details")';
var partial = $('#partial'); //cache it
$('.blog').click(function() {
    var id = $(this).data('id');
    partial.load(url, { x: id });
});