json TimeSpan return object

2019-07-23 06:29发布

问题:

I work with Asp.net MVC4 (C#), I want to load data from controller to view. from controller return an object in view, this object has an attribute of type TimeSpan (HH:DD:MM) this is my function:

public JsonResult Buscar(string id){
        string Mensaje = "";
        Models.cSinDenuncias oDenuncia = new Models.cSinDenuncias();
        oDenuncia.sd_iddenuncia = id;
        var denuncia = Servicio.RecuperaDenuncia<Models.cSinDenuncias>(ref Mensaje, oDenuncia.getPk(), oDenuncia);
        return Json(denuncia);
    }

denuncia.sd_horadenuncia has for example this value 18:03:53 but I can't load this value when show in the view this is the value [OBJECT OBJECT] In the view (Html.TextBoxFor):

$('#HoraDen').val(data.sd_horadenuncia);

How I can recover the correct value? (HH:MM:SS) and not [OBJECT OBJECT]

Regards Ricardo

回答1:

A TimeSpan is a complex type. This means that in your JSON it is serialized as such:

{
    "sd_horadenuncia": {
        "Ticks": 3000000000,
        "Days": 0,
        "Hours": 0,
        "Milliseconds": 0,
        "Minutes": 5,
        "Seconds": 0,
        "TotalDays": 0.003472222222222222,
        "TotalHours": 0.08333333333333333,
        "TotalMilliseconds": 300000,
        "TotalMinutes": 5,
        "TotalSeconds": 300
    }
}

You are attempting to assign this complex object to a text field which obviously doesn't make sense.

You could use a view model on your controller action to preformat the value:

public ActionResult Buscar(string id)
{
    string Mensaje = "";
    Models.cSinDenuncias oDenuncia = new Models.cSinDenuncias();
    oDenuncia.sd_iddenuncia = id;
    var denuncia = Servicio.RecuperaDenuncia<Models.cSinDenuncias>(ref Mensaje, oDenuncia.getPk(), oDenuncia);
    return Json(new 
    { 
        formattedHoradenuncia = denuncia.sd_horadenuncia.ToString() 
    });
}

and then inside your view you could use the new property:

$('#HoraDen').val(data.formattedHoradenuncia);

Another possibility is to access individual properties of this complex object and format the value yourself:

var hours = data.sd_horadenuncia.Hours;
var minutes = data.sd_horadenuncia.Minutes;
var seconds = data.sd_horadenuncia.Seconds;
$('#HoraDen').val(hours + ':' + minutes + ':' + seconds);