我正在尝试在我的脚本部分添加附加我的变量,因为我的文件名是GUID格式。文件名位于隐藏字段中:
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"/>
在脚本部分,我试图获取这个隐藏的字段值:
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);
}
答案 0 :(得分:1)
我不确定你要做什么,但如果你想要razor代码和javascript,你可以把它放在你的视图中。显然这将不再是不引人注目的javascript。但要做你想做的事,这将有效。我点击它时添加了一个按钮,它调用该函数来显示连接的URL。
@{
ViewBag.Title = "Test";
var strFileName = Guid.NewGuid();
}
<input type="hidden" id="hiddenStringFileName" value="@strFileName" />
<button onclick="fncAnnouncementLoad()">Show</button>
<script>
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;
alert(src);
}
</script>