MisaelGaray
MisaelGaray

Reputation: 75

Convert HTML input time to TimeSpan

I can't convert the value of a input type TIME in html to TimeSpan in a MVC controller with C#. I'm sending the input values with Jquery .

<div class="row">
            <div class="col-md-6">
                <label>Hora inicio: </label><input type="time" class="form-control" ng-model="hora.inicioc" /> 
            </div>
            <div class="col-md-6">
                <label>Hora fin: </label><input type="time" class="form-control" ng-model="hora.finc" />
            </div>
        </div>  

And My Jquery is:

$scope.AddReg = function () {
        AddProduccion();
        $.ajax
        ({
            type: "POST",
            //the url where you want to sent the userName and password to
            url: 'http://localhost:2713/Produccion/AgregarProduccion/',
            contentType: "application/json; charset=utf-8",
            async: true,
            //json object to sent to the authentication url
            data: JSON.stringify({dp : $scope.materiales, p :$scope.produccion}),
            success: function () {

            alert("Se agregó registro de produccion");
            }
        })
    };

And before do this, i push the ng-models to an array of objects to send it with Jquery.

var AddProduccion = function () {
        $scope.produccion.push(
            {
                hora_inicio_congelacion: $scope.hora.inicioc,
                hora_fin_congelacion: $scope.hora.finc,
                hora_inicio_deshielo: $scope.hora.iniciod,
                hora_fin_deshielo: $scope.hora.find,
                hora_registro: "",
                total_producido: 5,
                total_merma: 5
            }
        );
    };

And My controller is gettig two Lists of objects.

[HttpPost]
    public ActionResult AgregarProduccion(List<DetalleProduccionBolsasViewModel> dp, List<PBolsasModel> p)

where my PBolsasModel is

public class PBolsasModel
{
    public System.TimeSpan hora_inicio_congelacion { get; set; }
    public System.TimeSpan hora_fin_congelacion { get; set; }
    public System.TimeSpan hora_inicio_deshielo { get; set; }
    public System.TimeSpan hora_fin_deshielo { get; set; }
    public System.DateTime hora_registro { get; set; }
    public double total_producido { get; set; }
    public double total_merma { get; set; }
}

I already tried to set the hour_inicio_congelacion, hora_fin_congelacion as string and then convert their but i got an error because the value I'm getting from the view have not the format to convert it to TimeSpan. I tried also to cry.

Upvotes: 0

Views: 5982

Answers (1)

Irfan Ashraf
Irfan Ashraf

Reputation: 2460

I do it like this

<input type="text" name="StartTime" value="20:45" />

C# / MVC

public TimeSpan StartTime {get; set;}

In my case I was using bootstrap timepicker & format is set to 24hrs. Make sure you are using type="text" and time format is set to 24Hrs.

Upvotes: 1

Related Questions