How and how to return to the main page without losing page data

Ashkan 61 Reputation points
2024-07-22T17:53:32.98+00:00

The page is made with Asp.Net Core Razor Page, In this page >> MAINPAGE

(Please see the picture)

Untitled

1- Populate data and filling dropdown1

Here are the codes:

 public SelectList TermList { get; set; }
 public SelectList CourseList { get; set; }

 [BindProperty(SupportsGet = true)]
 public int Year { get; set; }


 private readonly DbkabirContext db;

 public CourseLernersListModel(DbkabirContext context)
 {
     db = context;
 }

 public void OnGet()
 {    
     var term = db.Terms.GroupBy(x => x.Year).Select(x => x.FirstOrDefault());
     TermList = new SelectList(term, "Year", "Year");
 }

html:

  <select class="form-select" id="ddterm" asp-for="Year" asp-items="Model.TermList">
      <option value="">سال</option>
  </select>

2- Select item from dropdown1 and fill dropdown2 (by relational tables)

 <script type="text/javascript">

    $("#ddterm").change(function () {
         $("#ddcourses").empty();
         var termyear = $("#ddterm").val()
         $.ajax({
             cache: false,
             type: "GET",
             url: "/CourseLernersList?handler=FillCourses",
             data: { "termYear": termyear },
             success: function (json, textStatus) {
                 $("#ddcourses").empty();
                 json = json || {};
                 for (var i = 0; i < json.length; i++) {
                     $("#ddcourses").append('<option value="' + json[i].value + '">' + json[i].text + '</option>');
                 }
                 $("#ddcourses").prop("disabled", false);
             },
             error: function () {
                 alert("اطلاعات وجود ندارد");
             }
         });

     })
     
 </script>

  public ActionResult OnGetFillCourses(int termYear)
  {
             
      CourseList = new SelectList(course, "Id", "CourseTitle");
      return new JsonResult(CourseList);
  }

3- click on button3 and load datat to table4 (datatable) by partialview

 <partial name="_CourseLearnersListPartial" model="@Model.RegInCourse1" />

 <script type="text/javascript">


    $("#btnShow").click(function () {
         var selectCourse = $("#ddcourses").val();
         $.ajax({
             url: "/CourseLernersList?handler=LoadPartial",
             type: "Get",
             dataType: 'html',
             data: { selcourse: selectCourse },
             contentType: 'application/json; charset=utf-8',
             success: function (result) {
                 $("#dt-nofnoh").html(""); //clear the fachinfo container.
                 $("#dt-nofnoh").html(result); //populate the container.
             },
             error: function (result) {
                 alert(result);
             }
         });
     });
     
 </script>

 public PartialViewResult OnGetLoadPartial(string selcourse)
 {
     if (selcourse != null)
     {
     
         RegInCourse1 = db.RegInCourses.Where(m => m.CourseId == courseId).Select(x => new RegInCourseViewModel
         {
             Id = x.Id,
             LearnerTitle = uniform.GetUserFullNameNatNoBY(db, x.UserIdLearner),
             ChooseServTitle = x.ChooseServ.Title,
             RegDateTime = x.RegTime + " " + x.RegDate.ToString().ToShamsi(),
             IsDisconnected = x.IsDisconnected,
             ReferToManager = x.ReferToManager,
             IsConfirmed = x.IsConfirmed
         }).ToList();
         return Partial("_CourseLearnersListPartial", RegInCourse1);
     }
     return Partial("_CourseLearnersListPartial", null);
 }

4- Clicking on button5 will open another page (We name this page Edit Page) and a number of fields will be edited and saved by the user.

So far everything is working properly and well and there is no problem

But my question and better to say, my problem is that I don't know how to go back to this page (MAINPAGE) after the data is saved (the same page that I posted a picture of)

so that the data of dropdowns and datatable are not lost and remain on this page.

I mean, what should I write for the Save Data and Return to MainPage buttons?

 <div class="form-actions">
     <a class="btn btn-secondary" asp-page="???" asp-page-handler="???" asp-route-id="@Model.command.Id">
         <i class="fas fa-angle-right"></i>
         Return to MainPage
     </a>
     <button type="submit" class="btn btn-success">
         <i class="icon-check"></i>
         Save Data
     </button>
 </div>

Thanks,

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

Accepted answer
  1. Ping Ni-MSFT 3,615 Reputation points Microsoft Vendor
    2024-07-23T07:22:59.0833333+00:00

    Hi @Ashkan,

    For save the data, you could use RedirectToPage with the parameter Yearand CourseId . For the back to the main page, you could use asp-route-Year and asp-route-CourseId.

    Not sure how is your real model design and relationships. Here is a whole working demo you could follow:

    Model design

     public class Term
      {
          public int Id { get; set; }
          public int Year { get; set; }
          // Other properties as needed
      }
      public class Course
      {
          public int Id { get; set; }
          public string? CourseTitle { get; set; }
          public int TermYear { get; set; }  // Foreign key to Term
          public Term? Term { get; set; }
          // Other properties as needed
      }
      public class RegInCourse
      {
          public int Id { get; set; }
          public int CourseId { get; set; }  // Foreign key to Course
          public string? UserIdLearner { get; set; }
          public DateTime RegDate { get; set; }
          public string? RegTime { get; set; }
          public bool IsDisconnected { get; set; }
          public bool ReferToManager { get; set; }
          public bool IsConfirmed { get; set; }
          public Course? Course { get; set; }
          // Other properties as needed
      }
      public class RegInCourseViewModel
      {
          public int Id { get; set; }
          public string? LearnerTitle { get; set; }
          public string? ChooseServTitle { get; set; }
          public string? RegDateTime { get; set; }
          public bool IsDisconnected { get; set; }
          public bool ReferToManager { get; set; }
          public bool IsConfirmed { get; set; }
      }
    

    CourseLernersList.cshtml

    @page
    @model RazorPagesProj.Pages.CourseLernersListModel
    <select class="form-select" id="ddterm" asp-for="Year" asp-items="Model.TermList">
        <option value="">سال</option>
    </select>
    <select class="form-select" id="ddcourses" asp-for="CourseId" asp-items="Model.CourseList" disabled>
        <option value="">Course</option>
    </select>
    <button type="button" id="btnShow">click</button>
    <div id="dt-nofnoh">
        <partial name="_CourseLearnersListPartial" model="@Model.RegInCourse1" />
    </div>
    @section Scripts
    {
        <script type="text/javascript">
            $("#ddterm").change(function () {
                 $("#ddcourses").empty();
                 var termyear = $("#ddterm").val()
                 $.ajax({
                     cache: false,
                     type: "GET",
                     url: "/CourseLernersList?handler=FillCourses",
                     data: { "termYear": termyear },
                     success: function (json, textStatus) {
                         $("#ddcourses").empty();
                         json = json || {};
                         for (var i = 0; i < json.length; i++) {
                             $("#ddcourses").append('<option value="' + json[i].value + '">' + json[i].text + '</option>');
                         }
                         $("#ddcourses").prop("disabled", false);
                     },
                     error: function () {
                         alert("اطلاعات وجود ندارد");
                     }
                 });
             })
            $("#btnShow").click(function () {
                var selectCourse = $("#ddcourses").val();
                $.ajax({
                    url: "/CourseLernersList?handler=LoadPartial",
                    type: "Get",
                    dataType: 'html',
                    data: { selcourse: selectCourse },
                    contentType: 'application/json; charset=utf-8',
                    success: function (result) {
                        $("#dt-nofnoh").html(""); //clear the fachinfo container.
                        $("#dt-nofnoh").html(result); //populate the container.
                    },
                    error: function (result) {
                        alert(result);
                    }
                });
            });
        </script>
    }
    

    CourseLernersList.cshtml.cs

    public class CourseLernersListModel : PageModel
    {
        public SelectList TermList { get; set; }
        public SelectList CourseList { get; set; }      
        public List<RegInCourseViewModel> RegInCourse1 { get; set; } = new List<RegInCourseViewModel>();
    
        [BindProperty(SupportsGet = true)]
        public int Year { get; set; }    
        [BindProperty(SupportsGet = true)]    //be sure add this attribute and property
        public int? CourseId { get; set; }   
    
        private readonly DbkabirContext db;
        public CourseLernersListModel(DbkabirContext context)
        {
            db = context;
        }
        public void OnGet()
        {
            var term = db.Term.GroupBy(x => x.Year).Select(x => x.FirstOrDefault());
            TermList = new SelectList(term, "Year", "Year");
            //add the following code
            if (Year != 0)
            {
                var courses = db.Course.Where(c => c.TermYear == Year).ToList();
                CourseList = new SelectList(courses, "Id", "CourseTitle");
                if (CourseId.HasValue)
                {
                    CourseList = new SelectList(courses, "Id", "CourseTitle",CourseId);
                     RegInCourse1 = db.RegInCourses.Where(m => m.CourseId ==CourseId).Select(x => new RegInCourseViewModel
     {
         Id = x.Id,
         LearnerTitle = "title" + x.Id,
         ChooseServTitle = "ChooseServTitle" + x.Id,
         RegDateTime = x.RegDate.ToString(),
         IsDisconnected = x.IsDisconnected,
         ReferToManager = x.ReferToManager,
         IsConfirmed = x.IsConfirmed
     }).ToList();          
                }
            }
        }
        public ActionResult OnGetFillCourses(int termYear)
        {
            var course = db.Course.Where(x => x.TermYear == termYear);
            CourseList = new SelectList(course, "Id", "CourseTitle");
            return new JsonResult(CourseList);
        }
        public PartialViewResult OnGetLoadPartial(string selcourse)
        {
            int courseId = int.Parse(selcourse);
            if (selcourse != null)
            {
                RegInCourse1 = db.RegInCourses.Where(m => m.CourseId == courseId).Select(x => new RegInCourseViewModel
                {
                    Id = x.Id,
                    LearnerTitle = "title"+x.Id,
                    ChooseServTitle = "ChooseServTitle" + x.Id,
                    RegDateTime = x.RegDate.ToString(),
                    IsDisconnected = x.IsDisconnected,
                    ReferToManager = x.ReferToManager,
                    IsConfirmed = x.IsConfirmed
                }).ToList();
                return Partial("_CourseLearnersListPartial", RegInCourse1);
            }
            return Partial("_CourseLearnersListPartial", null);
        }
    }
    

    _CourseLearnersListPartial.cshtml

    @model List<RegInCourseViewModel>
    @if (Model != null && Model.Count > 0)
    {
        <table class="table table-striped">
            <thead>
                <tr>
                    <th></th>
                    <th>Id</th>
                    <th>Learner Title</th>
                    <th>Choose Service Title</th>
                    <th>Registration Date</th>
                    <th>Is Disconnected</th>
                    <th>Refer to Manager</th>
                    <th>Is Confirmed</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            <a asp-page="/EditPage" asp-route-id="@item.Id" class="btn btn-primary">
                                Edit
                            </a>
                        </td>
                        <td>@item.Id</td>
                        <td>@item.LearnerTitle</td>
                        <td>@item.ChooseServTitle</td>
                        <td>@item.RegDateTime</td>
                        <td>@item.IsDisconnected</td>
                        <td>@item.ReferToManager</td>
                        <td>@item.IsConfirmed</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    else
    {
        <div>No data available</div>
    }
    

    EditPage.cshtml

    @page "{id:int}"
    @model RazorPagesProj.Pages.EditPageModel
    <h2>Edit Course</h2>
    <form method="post">
        <input asp-for="EditCourse.Id" hidden />
        <div class="form-group">
            <label asp-for="EditCourse.UserIdLearner"></label>
            <input asp-for="EditCourse.UserIdLearner" class="form-control" />
            <span asp-validation-for="EditCourse.UserIdLearner" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="EditCourse.RegTime"></label>
            <input asp-for="EditCourse.RegTime" class="form-control" />
            <span asp-validation-for="EditCourse.RegTime" class="text-danger"></span>
        </div>
       
        <!-- Add other fields as necessary -->
        <div class="form-group">     
            <div class="form-actions">
                <a class="btn btn-secondary" asp-page="/CourseLernersList" asp-route-CourseId="@Model.EditCourse.CourseId" asp-route-Year="@Model.EditCourse.Course.TermYear">
                    <i class="fas fa-angle-right"></i>
                    Return to MainPage
                </a>
                <button type="submit" class="btn btn-success">
                    <i class="icon-check"></i>
                    Save Data
                </button>
            </div>
        </div>
    </form>
    

    EditPage.cshtml.cs

      public class EditPageModel : PageModel
      {
          private readonly DbkabirContext db;
          public EditPageModel(DbkabirContext context)
          {
              db = context;
          }
          [BindProperty]
          public RegInCourse EditCourse { get; set; }
          public IActionResult OnGet(int id)
          {
              EditCourse = db.RegInCourses.Include(a=>a.Course).Where(x=>x.Id==id).First();
              if (EditCourse == null)
              {
                  return NotFound();
              }
              return Page();
          }
          public IActionResult OnPost()
          {
              if (!ModelState.IsValid)
              {
                  return Page();
              }
              //do database operation...
              // Redirect back to the main page with the state preserved
              return RedirectToPage("/CourseLernersList", new { termYear = EditCourse.Course.TermYear, courseId = EditCourse.CourseId });
          }
      }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Ashkan 61 Reputation points
    2024-07-23T04:54:25.7233333+00:00

    OR Is it possible to show the Edit Page as a modal and edit data then close it (thats mean Return to MainPage), does it have an effect on not emptying the data on the main page???

    0 comments No comments