skip to Main Content

GitHub Repo: https://github.com/shadowwolf123987/Gun-Identification-App

I am attempting to pass the values of two C# variables from the code block defined in my view to the html tags inside of the same view but the values are not being passed to the html tags.

The problem is in the GunView.cshtml file:

@using Microsoft.AspNetCore.Http
@using Azure.Core;
@System;
@System.Web;

<!DOCTYPE html>
<html lang="en">

@{
    string name = (string)ViewBag.name;
    string image = (string)ViewBag.image;

    Console.WriteLine(image);
    Console.WriteLine(name);
}

<body>
    <div>
        <img src="@image">
        <h1>@name</h1>
        <h1>TEST</h1>
    </div>
</body>
</html>

Neither the image nor name variable are passed to the html tags and are left blank. But the write lines correctly output the values of the variables and when changing the name variable to a string
(EG. string name = "test";), it is correctly displayed in the html tag.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to the answer supplied by Reddit user @XRay2212xray on my Reddit post, I was able to solve the issue. Thanks all for your assistance and help. https://www.reddit.com/r/programminghelp/comments/15pyid0/trying_to_use_c_razer_variable_in_html_tag_aspnet/

    His answer:

    The issue is that you are using an Ajax call to invoke the url and then redirecting the user to the same url. The ajax call is passing the value of gun but the redirect isn't, so when you redirect, the value of gun is empty rather then "handguns" so you aren't going into the code that sets the viewbag. You can fix it by adding ?gun=" + gun to the window.location.href as noted below:

    function sendView() {
            var gun = document.getElementById("guns").value
            $.ajax({
                url: "/Main/GunView",
                type: "GET",
                data: {
                    gun: gun
                },
                success: function (data) {
                    window.location.href = "/Main/GunView?gun=" + gun
                },
            });
        }
    

  2.        <img src="@ViewBag.image">
           <h1>@ViewBag.name</h1>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search