Home > Software design >  Parameter stay on Input Razor C#
Parameter stay on Input Razor C#

Time:09-16

I have a View like:

<form method="post" asp-action="Index">
   <input id="sStartDate" name="sStartDate" /><br>
   <input id="sFinishDate" name="sFinishDate" /><br>
   <input type="submit" class="btn btn-sm btn-primary btn-block" value="Generate" />

   <table>
      <!-- somedatahere... -->
   </table>
</form>

Then I have a Controller like:

public IActionResult Index(DateTime sStartDate, DateTime sFinishDate)
{
     var model = _db.Activities.Where(w => w.StartDate >= sStartDate && w.StartDate <= sFinishDate).ToList();
     return View(model);
}

My question:

  1. How can I set the sStartDate and sFinishDate input with a default date for today?
  2. When I clicked Generate, the input value should be stay as user selected. How can I do that?

Right now, When I click the sStartDate and sFinishDate then Generate. The input is set to null.

Need advice please.
Thank you.

CodePudding user response:

You can use TempData to keep the date:

View(ToShortDateString() is used to display date without time, if you want to display time, just remove this method):

@{
    var sStartDate = TempData["sStartDate"] == null ? DateTime.Now.ToShortDateString() : TempData["sStartDate"];
    var sFinishDate = TempData["sFinishDate"] == null ? DateTime.Now.ToShortDateString() : TempData["sFinishDate"];
}
<form method="post" asp-action="Index">
    <input id="sStartDate" name="sStartDate" value="@sStartDate" /><br>
    <input id="sFinishDate" name="sFinishDate" value="@sFinishDate"/><br>
    <input type="submit" class="btn btn-sm btn-primary btn-block" value="Generate" />
</form>

Controller:

[HttpPost]
public IActionResult Index(DateTime sStartDate, DateTime sFinishDate)
{
    TempData["sStartDate"] = sStartDate.ToShortDateString();
    TempData["sFinishDate"] = sFinishDate.ToShortDateString();
    return View();
}
  • Related