Reputation: 1956
ViewBag.Image = '<image>https://c152688.ssl.cf3.rackcdn.com/tcthh/v10/bg/light/random/singaporecity_light_1280.jpg'
I am trying to pass an image URL from controller to view using viewbag. In the view I am trying to assign the value to a div.
<script>
$('#logindiv').css("background-image", "url('" + @ViewBag.Image + "')");
</script>
But the above line gives me
Uncaught SyntaxError: missing ) after argument list error.
Upvotes: 0
Views: 344
Reputation: 337560
The first issue is that the image URL should not have the <image>
tag in it. That needs to be removed.
The second issue is that you're appending the content from the ViewBag on the server side. As such you don't need to concatenate it to the client side JS. You just need to output it in the correct position within the JS.
ViewBag.Image = 'https://c152688.ssl.cf3.rackcdn.com/tcthh/v10/bg/light/random/singaporecity_light_1280.jpg'
jQuery($ => {
$('#logindiv').css("background-image", 'url("@ViewBag.Image")');
});
Note that the JS has to run after the DOM has loaded, which is why I added the document.ready handler, and also the JS needs to be executed within the View so that the @
Razor/Blazor syntax will be interpreted. If your JS is contained within an external .js
file, your current approach will not work.
Upvotes: 1
Reputation: 326
Please try this
$('#logindiv').css("background-image", 'url(" + @ViewBag.Image + ")');
Upvotes: 0