问题
I have a Razor for loop:
@foreach (var user in Model.Users)
{
<p class="active-text">Active: @user.LastActive</p>
}
I've just installed moment.js to format this DateTime() date using js.
How can I pass the Razor model into a javascript function? I do have a JS viewmodel for this page, I'm just trying to avoid serializing the entire Model just because I need to apply some JS to a single field. How my viewModel stands right now:
<script type="text/javascript">
$(document).ready(ko.applyBindings(new SubjectVm()));
</script>
回答1:
I would wrap the date text in another span for later processing:
<p class="active-text">Active: <span class="active-text-date">@user.LastActive</span></p>
Then loop through and apply the formatting, inside document.load:
<script>
$(document).ready(function() {
$(".active-text-date").each(function() {
var date = $(this).text();
var formatted = moment(date).calendar();
$(this).text(formatted);
});
});
</script>
来源:https://stackoverflow.com/questions/19506012/how-to-turn-razor-model-into-js-object-in-a-razor-for-loop