Advertisement
otkalce

State storage - form

Mar 20th, 2023
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | Source Code | 0 0
  1. // *** This goes to Program.cs - use static file middleware ***
  2. app.UseStaticFiles();
  3.  
  4. // *** Create wwwroot folder in project and a new index.html file in it. ***
  5. // *** This goes to index.html ***
  6. <!DOCTYPE html>
  7. <html>
  8. <head>
  9.     <meta charset="utf-8" />
  10.     <title>Form example - receipt</title>
  11. </head>
  12. <body>
  13.     <form method="post" action="https://localhost:7246/api/Receipt/form">
  14.         <input type="hidden" name="ReceiptId" value="12" />
  15.         <select name="ReceiptTitle">
  16.             <option value="">(select subscription)</option>
  17.             <option value="0">Monthly Subscription</option>
  18.             <option value="1">Monthly Subscription - Family</option>
  19.             <option value="2">Quarterly Subscription</option>
  20.             <option value="3">Annual Subscription</option>
  21.         </select>
  22.         <br />
  23.         <input type="text" name="ReceiptTotal" placeholder="Total" />
  24.         <br />
  25.         <input type="submit" value="Update data" />
  26.     </form>
  27. </body>
  28. </html>
  29.  
  30. // *** Add the model for the form handler ***
  31. public class ReceiptFormData
  32. {
  33.     public int ReceiptId { get; set; }
  34.     public int? ReceiptTitle { get; set; }
  35.     public decimal? ReceiptTotal { get; set; }
  36. }
  37.  
  38. // *** Add the form handler to the controller ***
  39. [HttpPost("[action]")]
  40. public ActionResult<Receipt> Form([FromForm] ReceiptFormData data)
  41. {
  42.     var titles = new string[] { "Monthly Subscription", "Monthly Subscription - Family", "Quarterly Subscription", "Annual Subscription" };
  43.  
  44.     var retVal = _receipts.FirstOrDefault(x => x.Id == data.ReceiptId);
  45.     if (retVal == null)
  46.         return NotFound();
  47.  
  48.     if(data.ReceiptTitle.HasValue)
  49.         retVal.Title = titles[data.ReceiptTitle.Value];
  50.  
  51.     if (data.ReceiptTotal.HasValue)
  52.         retVal.Total = data.ReceiptTotal.Value;
  53.  
  54.     return Redirect("/index.html");
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement