0

I would like to pass Variables into an HTML screen and place on the screen. Currently using Net Core.

This question is only for regular .Net and does not seem to work. Pass Html String from Controller to View ASP.Net MVC

Test Controller:

_cardtitle = "Green Tree Title";
_cardtext = "Oak tree with leaves";
_imageurl = "https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"

public IActionResult Test(string _cardtitle, string _cardtext)
{

    ViewBag.CardTitle = _cardtitle;
    ViewBag.CardText = _cardtext;
    ViewBag.ImageURL= _imageurl;

    ViewBag.Cardstring = @"<div class=""card"" style=""width: 18rem;"" >
<img class=""card -img-top"" src =""https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"" alt =""Card image cap"" >
<div class=""card -body"" >
    <h5 class=""card -title"" > @ViewBag.CardTitle</h5>
    <p class=""card -text"">@ViewBag.CardText</p>
</div>
</div>";
    return View();
}

Test.cshtml

@Html.Raw(ViewBag.Cardstring)

Right now I only see @ Ampersand Variables,

Picture HTML Image

0

1 Answer 1

1

You are displaying your ViewBag wrong.

Change Html.Raw(ViewBag.Cardtest) to Html.Raw(ViewBag.Cardstring)

EDIT: According to my comments this should work for you. You need to pass @ViewBag.CardTitle and @ViewBag.CardText as properties not as part of string.

ViewBag.Cardstring = "<div class=\"card\" style=\"width: 180rem;\"><img class=\"card -img-top\" src =\"https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF_tree.jpg?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60\" alt =\"Card image cap\"><div class=\"card -body\" ><h5 class=\"card -title\" >" + @ViewBag.CardTitle +"</h5><p class=\"card -text\">" + @ViewBag.CardText + "</p></div></div>";
Sign up to request clarification or add additional context in comments.

4 Comments

sorry just fixed my question code, but does not solve underyling issue yet, same result
Remove @ while assigning raw html to ViewBag.Cardstring in Controller
this will cause syntax errors, need to contain html
Yes you need to add \ in front of double "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.