Willy David Jr Willy David Jr - 1 year ago 104
Javascript Question

Add Dynamic Variable in URL Content in JQuery

I am trying to add attach my variable on my script section, since my filename is in GUID format. The filename is in hidden field:

string strDirectory = Server.MapPath(Url.Content("~/Content/AnnouncementImages/"));
string[] strFiles = Directory.GetFiles(strDirectory);
string strFileName = string.Empty;
foreach (var strFile in strFiles)
strFileName = Path.GetFileName(strFile);
<img id="myImg" src="@Url.Content("~/Content/AnnouncementImages/" + strFileName)" width="300" height="200" />
<input type="hidden" id="hiddenStringFileName" value="@strFileName"/>

In script section, I am trying to get this hidden field value:

function fncAnnouncementLoad()
var filename = document.getElementById('hiddenStringFileName');

//This is not working so far since it says cannot resolve symbol filename on below code:
modalImg.src = '@Url.Content("~/Content/AnnouncementImages/" + filename);

Answer Source

I am not sure what you are trying to do but if you want razor code plus javascript, you can put it in your view. Obviously this will no longer be unobtrusive javascript. But to do what you want, this will work. I added a button when you click it, it calls the function to show the concatenated URL.

    ViewBag.Title = "Test";
    var strFileName = Guid.NewGuid();
<input type="hidden" id="hiddenStringFileName" value="@strFileName" />
<button onclick="fncAnnouncementLoad()">Show</button>
function fncAnnouncementLoad()
   var filename = document.getElementById('hiddenStringFileName').value;

   //This is not working so far since it says cannot resolve symbol filename on below code:
   var src = '@Url.Content("~/Content/AnnouncementImages/")' + filename;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download