json TimeSpan返回对象 [英] json TimeSpan return object

查看:112
本文介绍了json TimeSpan返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Asp.net MVC4(C#),我想从控制器加载数据以进行查看. 从控制器返回视图中的对象,此对象的属性类型为TimeSpan(HH:DD:MM) 这是我的功能:

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例如具有此值18:03:53,但是在视图中显示该值为[OBJECT OBJECT]时,我无法加载此值 在视图(Html.TextBoxFor)中:

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);

如何恢复正确的值? (HH:MM:SS)而不是[OBJECT OBJECT]

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

问候 里卡多

推荐答案

TimeSpan是一种复杂类型.这意味着在您的JSON中,它是这样序列化的:

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);

这篇关于json TimeSpan返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆