0

I have a JQuery function that reloads a div with a PartialView. In order to reuse it on different Views, I need to pass the name of the PartialView to the controller. Is there a way to get the name of the PartialView hosting a script?

Matias Masso
  • 1,670
  • 3
  • 18
  • 28
  • which portion of the code are you trying to reuse? The jquery code or the controller's actionresult method that switches between partial view based the view name you pass? so if I get it correctly, do all the partialviews have the jquery function that reloads a div? – Dennis R Jun 22 '14 at 02:53
  • I usually use the `data:` portion of the `$.ajax` request to pass in any additional value I would need in the controller like `data: JSON.stringify({ partialname: $('#viewname').val() })` – Dennis R Jun 22 '14 at 02:59
  • Hi Dennis, the JQuery function reacts to pagination click to ask the controller for next page. I can add a parameter to pass the name of the partialview but I was wondering if there was any way so the function may pass it by its own – Matias Masso Jun 22 '14 at 15:07
  • Ok, I get it. May be you can consider using [PagedList](https://www.nuget.org/packages/PagedList.Mvc/4.5.0) for you pagination. – Dennis R Jun 23 '14 at 04:22
  • Thanks Dennis, I'll investigate about PagedList – Matias Masso Jun 25 '14 at 11:53
  • Glad to help. I have another post of working sample [here](http://stackoverflow.com/questions/22924565/how-to-load-first-x-items-and-give-user-the-option-to-load-more-in-mvc-net/22925898#22925898) on how to use pagedlist in your mvc razor view – Dennis R Jun 25 '14 at 16:34

2 Answers2

1

Here is how you can get the name of the partial hosting a script. Write this in the partial view hosting the script and you can access the viewname in your jquery function.

<script type="text/javascript">
    // get the view name withought the file name extension
    var viewname = '@Path.GetFileNameWithoutExtension(Server.MapPath(VirtualPath))'; 
    alert(viewname);
</script>
Dennis R
  • 3,195
  • 1
  • 19
  • 24
0

I usually add something similar to below:

$('#user').on('keyup', function (e) {
    var sel = $('#dog');
    var inp = $(this).val();

    if (e.keyCode == 13) {
      e.preventDefault();
      return false;
    }

    $.post('@Url.Action("SearchList", "Admin")/' + inp, function (data) {
      sel.show();
      sel.html(data);
    });

  }).on('keydown', function (e) {
    if (e.keyCode == 13) {
      e.preventDefault();
      return false;
    }
  });

Look mostly at the $.post(....) . If the JQuery is on the same page, you can use the @Url.Action to provide the address to tell it to reload a partial.

Damon Drake
  • 839
  • 1
  • 10
  • 23