1

I'm new to C#, JS, jQuery, etc. For a schoolproject I'm building a cinema-website with ASP.NET and C#.
I have come to the point that I think I'm close to the answer, but I can't figure it out.

What is the problem?
At the Index-page of the website the customer can pick a movie to go to the next screen to buy the tickets. There he needs to pick a moment of the movie from a dropdownmenu. The dropdownmenu-code looks like this:

<div class="form-group" style="width: 30%">
   @Html.LabelFor(m => Model.Showtime, new { @class = "control-label col-md-2" })
   <div>
      @Html.DropDownListFor(m => Model.Showtime!.StartAt, new SelectList(Model.ShowList, "Value", "Text"), "Select show", new { @class = "form-control", id = "showList"  })
   </div>
</div>

I've created a jQuery function that gets the picked Showtime from the dropdownmenu.
This function looks like this:

<script>
$("#showList").change(function() {
    
    var selectedVal = $(this).val();
   
    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        url: '/Orders/GetPickedShowtime/',
        data: {showTimeId: selectedVal},
    
        success:
        function(response) {
            
            response = JSON.stringify(response)
            $('#testShowtime').text(response)
        },
    
        error:
        function(response) {
          console.log("ERROR: ", response)
        }
    });
})
</script>

In the controller I wrote a function to get the picked Showtime object from the database:

public ActionResult<Showtime> GetPickedShowtime(int showTimeId) {
        
   var show = _context.Showtime!
      .Where(s => s.Id == showTimeId);

   return Json(show);
}

I used this code: $('#testShowtime').text(response) in my jQuery to test the function in my View with: <h4 id="testShowtime"></h4>. It works. It gives a Array back to the View, like:

[{"id":6987,"startAt":"2022-03-13T18:00:00Z","hallId":3,"movieId":1,"hall":null,"movie":null}]

GREAT! The function seems to work. But what I want to do now is to get the Object from this Json-string into a C# variable. If the customer selects a showtime and some tickets, a button brings them to the next page where the seatselection begins. So the variable with the picked Showtime needs to go there by clicking a button.... And now I'm stuck.

Could someone help me out of this puzzle? I'll buy you a beer :P

iFritsWester
  • 91
  • 1
  • 7
  • Think about what will happen when you post your page (with the DropDownList selected). The value selected will be used to fill an instance of the model declared for the page and this instance is received on the server side. You should simply read again that value and you have your info – Steve Mar 12 '22 at 08:55
  • Do you mean like this? @{ var pickedShowtime = Model!.PickedShowtime!.Result; } – iFritsWester Mar 12 '22 at 08:59
  • _a button brings them to the next page_ How do you go to the next page? Do you use a submit button that sends the inputs on your current page to some controller action (or razor page code behind)? Please show how do you handle this action – Steve Mar 12 '22 at 09:05
  • The button ain't finished yet. I need to pass the buyed ticketinfo in the button later. – iFritsWester Mar 12 '22 at 09:09
  • This will call an action on the Seats controller named index. In this action you try to pass whe ShowTimeId. Then you have the means to reask your database about the info needed. – Steve Mar 12 '22 at 09:15
  • Oke, What I also would like to do, and that's why I want the result in a variable, is to check the available seats in the hall for this show, so the customer is not able to buy 10 tickets when only 6 seats available. So when the Showtime-result is in a var, I can use the var for more things. – iFritsWester Mar 12 '22 at 09:24
  • Then just add another AJAX call to check for available seats before jumping to the seat selection page. It is up to the jquery code to show an error message if there are not enough seats and change the number of seats choosen to the max value allowed. (However this will not prevent errors if, in the meantime, someone else buys seats for the same time. You still need to check on the controller side) – Steve Mar 12 '22 at 09:28
  • Also, I think that you should have ShowTimeViewModel class where your server side code add the info from the ShowTime extracted from the database AND the available seats for that time. – Steve Mar 12 '22 at 09:37

1 Answers1

1

You can use Session variable to store your StoreTime on the server itself. AJAX is used to update a portion of the page without reloading the entire page and in your case, you are unnecessarily complicating things. You can do the following:

In your method, define a Session variable which is always updated when the user selects from the dropdown:

public ActionResult<Showtime> GetPickedShowtime(int showTimeId) {
        
   var show = _context.Showtime!.Where(s => s.Id == showTimeId);

   if(show != null)
   {
     Session["myCurrentShow"] = show;
   }

   return Json(show);
}

Now once your Session is defined, you can access it on your next ActionMethod. I am giving an example how you would use this Session variable on your last step:

public ActionResult ConfirmShowTime() {

   if(Session["myCurrentShow"] != null)
   {
     Showtime showtime = new Showtime();
     //Cast your session here to get the values
     showtime = (Showtime)Session["myCurrentShow"];
   }  
   
   // Your logic
   return View();
}
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
  • I'd love to try that, but my project won't recognize Session. What do I need to do to enable Session? I tried to add: "@using System.Web.HttpContext.Current.Session" but it can't resolve HttpContext. – iFritsWester Mar 12 '22 at 13:52
  • @iFritsWester You have to declare this namespace: `using System.Web.Mvc;` – Rahul Sharma Mar 12 '22 at 13:58
  • I tried that but it says: Cannot resolve symbol 'Mvc' – iFritsWester Mar 12 '22 at 14:03
  • I'm using Rider by the way. Do I need to download a specific Nuget package? – iFritsWester Mar 12 '22 at 14:06
  • @iFritsWester You can download the `Microsoft.AspNet.Mvc` from Nuget manager. I am not sure how you have setup your project. – Rahul Sharma Mar 12 '22 at 14:11
  • Well, I have this four added to my Program.cs: builder.Services.AddMvc(); builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(); app.UseSession(); But it still won't work. – iFritsWester Mar 12 '22 at 14:13
  • @iFritsWester You can refer to this answer on how to use session in .net core: https://stackoverflow.com/a/55221661/1807452 – Rahul Sharma Mar 12 '22 at 15:00
  • Hi Rahul, No I did not get this working, so I created a workaround. I use localStorage.setItem now with JavaScript to store keys and values in local storage. – iFritsWester Mar 15 '22 at 12:30
  • @iFritsWester So how are you managing it on your server side? Localstorage is only on client side and cannot be accessed by the server. – Rahul Sharma Mar 15 '22 at 12:36
  • 1
    I used JS to set the showtimeId as a JSON string. I added this behind the Url.Action to the controller of the next view. All the other data, like ticket quantity, will be sent via local storage. This will be returned in another view and passed back to a controller which creates the order. But we are students so I expect to get new problems elsewhere. We’ll learn the most by doing and trying :)) – iFritsWester Mar 15 '22 at 21:56