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!

15
  • Currently in your js code you're not making use of any sort of ajax at all Commented Aug 14, 2019 at 9:49
  • Is there any reason why you are not using a Html helper here? Commented Aug 14, 2019 at 9: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. Commented Aug 14, 2019 at 9:56
  • Have a look at this question it's a good pointer Commented Aug 14, 2019 at 9:57
  • Thank you, so I am guessing it is not as simple as I expected to change 1 value when the select value changes. Commented Aug 14, 2019 at 9:59

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

11 Comments

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 You can put the <script> part it in your .cshtml file.
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 Yes, I am assuming you are declaring the logic to get your ListOfPosts from somewhere?
@Andrew Can you come to the chat discussion ?
|
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>

Comments

-2

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

2 Comments

This is more of a comment than an answer.
@Yogendra I can't accept this as an answer, explanations would be good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.