Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# code in JQuery in ASP.NET razor view

I have a server-side model with a datetime type field PublishDate. I am sending List<Posts> as json in response to ajax call.

I would like to use c# code Convert.ToDateTime(this.PublishDate).ToString("MMM dd, yyyy") in jquery code. Below is my code what I tried so far-

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

But it's not working. Any idea?

like image 949
s.k.paul Avatar asked Feb 27 '26 02:02

s.k.paul


1 Answers

The whole point of using Razor is that you can use the power of C# in your html code, or cshtml to be more precise.

Assuming your div id is container, you can do this.

You have a member in your model class named PublishDate

Add this in HTML

<input id="container" name="@Html.DisplayNameFor(model => model.PublishDate)" value="@DateTime.PublishDate.ToString("MMM dd, yyyy")">

And remove the coversion from jQuery.

like image 134
CodePhobia Avatar answered Feb 28 '26 15:02

CodePhobia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!