1

I have got a page full of posts, I sort those posts before rendering it.

Now I have created a drop down so user's can sort the posts by newest or oldest. The only problem is I don't know how to update the server-side variable through Ajax.

    @{
       var SortSelected = "";

       var sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();

        if (SortSelected == "Most recent")
        {
            sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();
        }
        else if (SortSelected == "Oldest")
        {
            sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).ToList();
        }
   }

I have removed other code which is irrelevant to make it cleaner.

That's my code for the posts, this is the Razor(html)

 <div class="AnimatedLabel">
     <select name="contact" class="tm-md-12">
           <option id="hide-selector-dropdown" value=""></option>
              @foreach (var item in FilterTypes)
              {
                  <option value="@item">@item</option>
              }
       </select>
          <label for="contact">Sort by</label>
          <span class="tm-icon-arrow--right" id="selector-dropdown-arrow"></span>
 </div>

This is how I tried to do it -

<script>
 $('select').on('change', function () {
        SortSelected = this.value;
    });
</script>

But it is not updating the value, I have been told because it is server-side. I know people will probably roast me for this question but I do not know any other solution so any help would be great!

I do not have much experience with .net/c# Thanks!

Andrew
  • 695
  • 2
  • 9
  • 25
  • Currently in your js code you're not making use of any sort of ajax at all – Izzy Aug 14 '19 at 09:49
  • Is there any reason why you are not using a Html helper here? – JamesS Aug 14 '19 at 09:50
  • @Izzy I do not understand how to use Ajax, I wanted some pointers or any directions on how I could modify that variable if possible, sorry I am only new to this all. – Andrew Aug 14 '19 at 09:56
  • Have a look at [this](https://stackoverflow.com/questions/12480041/asp-net-mvc-sort-listing-by-selected-item-in-dropdownlist) question it's a good pointer – Izzy Aug 14 '19 at 09:57
  • Thank you, so I am guessing it is not as simple as I expected to change 1 value when the select value changes. – Andrew Aug 14 '19 at 09:59
  • @Andrew So basically you want to update your list contents on what is selected from the dropdownlist? Please correct if I am wrong here. – Rahul Sharma Aug 14 '19 at 10:04
  • @RahulSharma All I am trying to do when the select value changes, update the variable called `SortSelected = 'what-ever-has-been-chosen-goes-here'`. The reason I can't update the variable as I normally would when using maybe Javascript is because this seems to be server-side, so I'm not sure how to update the value of that variable. – Andrew Aug 14 '19 at 10:07
  • So am I right in understanding you want to select a value and post it to a controller method? – JamesS Aug 14 '19 at 10:14
  • Dear @Andrew, On the client-side, you have no access to C# code or variables. May be a better idea is to store your C# variable inside ``. Then, once the dropdown onChange event is launched, you need to change this hidden value and sort your `` according to that. – A. Nadjar Aug 14 '19 at 10:16
  • So at the moment all I have is a variable, in that funny looking `@{SortSelected = ""}` and I need to update that variable, how would you update it? Does it have to be done by using Ajax? @JamesS – Andrew Aug 14 '19 at 10:17
  • @Andrew And is this variable in a tag of some sort? – JamesS Aug 14 '19 at 10:17
  • So this is the best example I can give of the work - https://www.codepile.net/pile/dN7j5QK3 It is all in a .cshtml file – Andrew Aug 14 '19 at 10:19
  • Indeed the C# code can not be accessed on the client side, so how can I change that value or am I going about it wrong? Thanks @A.Nadjar – Andrew Aug 14 '19 at 10:23
  • The value to this `` is assigned once the view is rendered. Then on client-side, you can read or set value to it `$('input#---').val('fetch-From-DropDown')`. – A. Nadjar Aug 14 '19 at 10:27
  • I can change the dropdown value, but its the logic just before it which sorts the articles, that's where I need to change it but I don't have access via the client side, so I need to work with Ajax, I just wanted some pointers on that or if someone could show like a little example, many thanks! – Andrew Aug 14 '19 at 10:29

3 Answers3

1

Okay, so I just wanted to show you how you can achieve something like this using AJAX. As far as I have understood, you want to sort your posts list based on the selection from the user in the dropdown list that you have. Please refer to the code snippet below and let me know if you were able to get what you wanted regarding your requirement:

<script>
 $('select').on('change', function () {
//SortSelected = this.value;

//First get the text of the selected item
var selectedText=$('#hide-selector-dropdown :selected').text();

//Now generate your JSON data here to be sent to the server
  var json = {
              selectedText: selectedText
             };

//Send the JSON data via AJAX to your Controller method
    $.ajax({
        url: '@Url.Action("ProcessMyValue", "Home")',
        type: 'post',
        dataType: "json",
        data: { "json": JSON.stringify(json)},
        success: function (result) {
            //Show your list here
                if (data.success) {
                  console.log(data.sortedArticles);
                 }
                else {
                 console.log("List empty or not found");
                }
        },
        error: function (error) {
             console.log(error)
        }
      });
    });
</script>

Your Controller would look like:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult ProcessMyValue(string json)
{

        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        var SortSelected= jsondata["selectedText"];

        //Do something with your variables here. I am assuming this:

        var sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();

        if (SortSelected == "Most recent")
        {
         sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();
        }
        else if (SortSelected == "Oldest")
        {
          sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).ToList();
        }  

    return Json(new { success = true, sortedArticles }, JsonRequestBehavior.AllowGet);
}
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
  • Thank you very much for this - Do I need to put it into its own different files then, I can't just dump this into the cshtml file I am using? Thank you. – Andrew Aug 14 '19 at 10:44
  • @Andrew You can put the ` – Rahul Sharma Aug 14 '19 at 10:58
  • Just not the controller bit, I have created a controller for it. But the controller complains that it doesn't know what `ListOfPosts` is? – Andrew Aug 14 '19 at 10:59
  • @Andrew Yes, I am assuming you are declaring the logic to get your `ListOfPosts` from somewhere? – Rahul Sharma Aug 14 '19 at 10:59
  • Yeah its coming from the same file as where the script has been put, do I need to just get the logic and also put it in that controller? or how would I do this? I can share the whole file which will help you understand it all much more if you wish. – Andrew Aug 14 '19 at 11:01
  • This here is the whole file - https://gist.github.com/ElAndy94/f5ced426673825926068b4eba8bb189c – Andrew Aug 14 '19 at 11:04
  • @Andrew What you are trying to achieve on your razor page based on the selected value from dropdown is not possible. You can refer to this link for that: https://stackoverflow.com/questions/28317182/how-to-pass-a-value-to-razor-variable-from-javascript-variable .Meanwhile the same logic you would have to post in your controller to get your desired result. – Rahul Sharma Aug 14 '19 at 11:04
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/197923/discussion-between-andrew-and-rahul-sharma). – Andrew Aug 14 '19 at 11:08
  • The error was coming from this `var myListOfPosts = @sortedArticles;` – Andrew Aug 14 '19 at 13:13
  • No luck yet, as there is not other way I could get the values of `sortedArticles` – Andrew Aug 14 '19 at 13:16
  • 1
    @Andrew Can you come to the chat discussion ? – Rahul Sharma Aug 14 '19 at 13:17
0

You can't change server variable value but you can use this for refresh your table.

<script>
     $('select').on('change', function () {
            $.get('/Url' , {sortBy:this.value}).done(function(result){
             $('#yourTable').html(result);
            }).fail(function(){
                alert('Error !');
            });
        });
    </script>
-2

You can call web method in server side using ajax. Use that method to update variable on server side