简体   繁体   English

如何使用jquery访问视图中的模型对象?

[英]How do I access a model object in a view using jquery?

I'm just new with asp.net mvc using razor syntax in the view and I would like to know how can I use a model object inside a jQuery routine to set an img src? 我只是在视图中使用剃刀语法的asp.net mvc的新手,我想知道如何在jQuery例程中使用模型对象来设置img src?

For ex: 例如:

 setSourceImage()
    {
       @foreach(var myPaths in Model)
       {
        @: jQuery('#sampleImage').attr('src',myPaths.imgPath)
       }
    }

I know the syntax is wrong, but in a sense that is what I want to achieve. 我知道语法是错误的,但是从某种意义上讲,这是我想要实现的。

Thanks. 谢谢。

Yes, the syntax is wrong. 是的,语法错误。 I would recommend you using the Json.Encode method to safely serialize the property of your model you are interested in: 我建议您使用Json.Encode方法安全地序列化您感兴趣的模型的属性:

<script type="text/javascript">
    function setSourceImage() {
        var imageSources = @Html.Raw(Json.Encode(Model.Select(x => x.imgPath)));
        for (var i = 0; i < imageSources.length; i++) {
            jQuery('#sampleImage').attr('src', imageSources[i])
        }
    }
</script>

which might be rendered as: 可能呈现为:

<script type="text/javascript">
    function setSourceImage() {
        var imageSources = ['/images/img1.jpg', '/images/img2.jpg'];
        for (var i = 0; i < imageSources.length; i++) {
            jQuery('#sampleImage').attr('src', imageSources[i])
        }
    }
</script>

Obviously for this to work the imgPath property of your model should contain an absolute or relative url to the image on the server. 显然,要使其正常工作,模型的imgPath属性应包含服务器上图像的绝对或相对URL。 It should not contain the physical location of the image like c:\\inetpub\\wwwroot\\myapp\\images\\img1.jpg . 它不应包含图像的物理位置,例如c:\\inetpub\\wwwroot\\myapp\\images\\img1.jpg If this is the case you will have to transform this property on the server before rendering the view. 如果是这种情况,则必须在呈现视图之前在服务器上转换此属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM