[英]Serializing ISO8601 string to C# TimeSpan
My project is an ASP.Net MVC project. 我的项目是一个ASP.Net MVC项目。 In JavaScript, I have an ISO 8601 string, like
"PT15M"
. 在JavaScript中,我有一个ISO 8601字符串,如
"PT15M"
。 How do I define my model so that it gets properly serialized to a TimeSpan
object? 如何定义模型以便将其正确序列化为
TimeSpan
对象?
Here is my Javascript: 这是我的Javascript:
var model = new TemplateMapModel();
model.DelayBy = "PT15M";
if (PerformClientSideValidation(model)) {
$.ajax({
type: 'POST',
url: '/api/TemplateMap',
data: { templateMap: model, files: files },
success: function (result) {
$('#modalTemplateMap').modal('toggle');
},
error: function (xhr, textStatus, e) {
var error = xhr.responseJSON.Message;
ShowMessageBox("Error", error);
ToggleBusyIndicator(false);
},
complete: function (xhr, textStatus) {
TEMPLATEMAPPING.grid.reload();
}
});
}
I tried this in my model: 我在我的模型中试过这个:
public TimeSpan DelayBy { get; set; }
Doing this results in a null value. 这样做会产生空值。 I also tried this:
我也试过这个:
public string DelayBy { get; set; }
This will work, and then I can use XmlConvert.ToTimeSpan()
to get what I want, however, I would prefer not to do it this way because it doesn't seem like the correct way, having to declare my DelayBy as a string, then convert it in my business logic. 这将工作,然后我可以使用
XmlConvert.ToTimeSpan()
来获得我想要的东西,但是,我宁愿不这样做,因为它似乎不正确的方式,不得不将我的DelayBy声明为字符串,然后在我的业务逻辑中转换它。 I would like to use this definition: 我想用这个定义:
public TimeSpan DelayBy { get; set; }
and have MVC automatically convert it to and from a TimeSpan
object. 并让MVC自动将其与
TimeSpan
对象进行转换。 Any ideas? 有任何想法吗?
Try to define setter/getter
尝试定义
setter/getter
private TimeSpan _delayBy;
public TimeSpan DelayBy {
get {
return this._delayBy;
}
set {
this._delayBy = XmlConvert.ToTimeSpan(value.ToString());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.