我有一个服务器端模型,其日期时间类型字段为 PublishDate 。我正在发送List<Posts>
作为json以响应ajax调用。
我想在jquery代码中使用c#code Convert.ToDateTime(this.PublishDate).ToString("MMM dd, yyyy")
。以下是我到目前为止所尝试的代码 -
var posts = response.Posts;
$.each(posts, function () {
$('#container').append('<div class="row">
<div class="col-lg-12">
<h2>' + this.PostTitle + '</h2>
<span>Published on: @Convert.ToDateTime(this.PublishDate).ToString("MMM dd, yyyy")</span></div></div>');
});
但它没有用。有什么想法吗?
答案 0 :(得分:1)
使用Razor的重点在于你可以在你的html代码中使用C#的强大功能,或者更精确地使用cshtml。
假设您的div为container
,您可以这样做。
您的模型类中有一个名为PublishDate
在HTML中添加
<input id="container" name="@Html.DisplayNameFor(model => model.PublishDate)" value="@DateTime.PublishDate.ToString("MMM dd, yyyy")">
从jQuery中删除coversion。
答案 1 :(得分:1)
它可能对我有用。
试试这种格式:
Convert.ToDateTime(PublishDate, System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
答案 2 :(得分:0)
您不能以这种方式互用C#和jquery代码,原因很简单,在将数据发送到页面之前,C#代码在服务器端执行。
代表@Convert.ToDateTime(this.PublishDate)
的代码在类上查找名为PublishDate
的属性,该属性呈现剃刀页面并尝试将其转换为DateTime
对象。
要做的事情的一种方法是向模型中添加一个属性,该属性已经包含格式正确的日期,因此您不必费心使用Javascript解析它。
另一种方法是使用javascript解析它。 因为日期/时间对象是复杂而棘手的事情,并且可能会因跨浏览器的怪癖而烦恼,所以建议使用库来让您的生活更轻松。 一个好的起点是Moment.js
看起来像这样:
'<span> Published on: ' + moment(this.PublishDate).format('MMM dd , yyyy') + ' </span></div></div>'