我如何使用JavaScript函数剃刀值? [英] How do I use Razor values in a javascript function?

查看:132
本文介绍了我如何使用JavaScript函数剃刀值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  使用JavaScript 内剃须刀

我想向剃刀页的从模型siimple值,并用它作为一个JavaScript函数的恒定值。即。

I would like to place a siimple value from the model on a razor page and use it as a constant value in a javascript function. i.e.

<script> var myValue = @Model.myRecord.Count();</script>

让myvalue的=在我的模型记录计数。我使用myRecord.Count为例,它可能是从我的模型的任意值。

so that myValue = the record count in my model. I am using myRecord.Count as an example, it could be any value from my model.

这可能吗?

TIA
Ĵ

OK我遇到下述溶液中偶然发现:

OK I stumbled across the following solution:

<script> var myValue = @(Model.myRecord.Count())</script>

只是把在矿井额外的括号帮助。

Just putting inthe extra brackets helped.

推荐答案

当然,只要确保正确连接code吧。例如,你可以连接JSON code。整个模型本身:

Sure, just make sure to properly encode it. For example you could JSON encode the entire model itself:

@model IEnumerable<MyViewModel>
<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
    // at this stage the model javascript variable represents the JSON encoded
    // value of your server side model so that you can access all it's properties:
    alert(model.length);
</script>

alert(model[2].Foo.Bar);

或什么的。

但是,如果你只关心模型中元素的个数(如果这个模式再度presents集合):

But if you only care about the number of elements inside the model (if this model represents a collection):

var count = @Html.Raw(Json.Encode(Model.Count()));
alert(count);

这篇关于我如何使用JavaScript函数剃刀值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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