Home > Net >  How to convert seconds to minute and show it right after in label?
How to convert seconds to minute and show it right after in label?

Time:04-28

I need my user to enter the seconds as an input but right after the user enter it I want to convert seconds to minutes and show it to user in label. What am I missing here ?

View

@Html.BSMaterialTextBoxFor(model => model.seconds, "Enter the seconds",colCSS: "col-6", htmlAttributes: new { data_bindrop = "seconds" , autocomplete = "off" })
@Html.LabelFor(model => model.secondsStr)

ViewModel

  public int seconds{ get; set; }

  [Display(Name = "Time")]
   public string secondsStr
        {
            get
            {
                return (seconds/ 60).ToString()  " Minutes"  " "   (seconds% 60).ToString() "Seconds";
            }
        }         

 Next to time , it should write 0 minutes and 45 seconds

Next to time , it should write 0 minutes and 45 seconds

CodePudding user response:

There are even easier way to handle what you are trying to achieve. I hope this is what you are looking for: enter image description here

Please follow the steps below:

Model:

public class SecondModel
    {
        public double Seconds { get; set; }
    }

Controller For Display:

 public IActionResult Index()
        {

            ViewBag.Minutes = TempData["Minutes"];
            return View();
           
        }

Controller When Submit:

        [HttpPost]
        public async Task<IActionResult> AddSecond(SecondModel second)
        {
            TimeSpan t = TimeSpan.FromSeconds(second.Seconds);
            string convertedMinutes = string.Format("{0:D2}m:{1:D2}s", t.Minutes, t.Seconds);
            TempData["Minutes"] = convertedMinutes;
            return RedirectToAction("Index");
        }

Note: Point to rememebr in C# Or asp.net core there is a built in method to do that. I am just using TimeSpan.FromSeconds to implement that.

View:

@model DotNet6MVCWebApp.Models.SecondModel
<div >
    <div >
        <form  method="post" asp-controller="Second" asp-action="AddSecond">
            <table  style="border-spacing: 12px;">
                <tr>
                    <td><strong>Enter Seconds</strong></td>
                    <td><input asp-for="Seconds"  /></td>
                    <td><button type="submit" >Convert Second In Minutes</button></td>
                    <td>You have Entered-<strong>@ViewBag.Minutes</strong></td>
                </tr>
            </table>
        </form>

    </div>
</div>

Output:

enter image description here

  • Related