@ViewBag.EntryId
is a Razor directive. If you move your script into a JS file, Razor is no longer going to run anything. If you need to move this script to a separate file, you'll have to pass that entry ID into the script somehow.
SignalR not responding in MVC when script in a .js file
-
30-06-2022 - |
Question
I have an ASP.NET MVC app that uses SignalR. It works fine when the client script that deals with SignalR is inline, but if I extract the scripts to a .js file it does not receive calls from the server.
@model LiveContentSample.Models.Entry
@{
ViewBag.Title = "Details SignalR";
ViewBag.EntryId = Model.Id;
}
<h2>Details with PartialView SignalR Comments</h2>
<fieldset>
<legend>Entry</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Title)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Title)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Content)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Content)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
@Html.Action("_GetForEntryWithSignalR", "Comment", new { entryId = @Model.Id })
@section scripts {
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script src="~/Scripts/jquery.signalR-1.1.3.min.js"></script>
<script src="~/signalr/hubs"></script>
@* <script type="text/javascript" src="~/Scripts/CommentsSignalR.js"></script>*@
<script>
$(function () {
var entryId = '@ViewBag.EntryId';
var commentHub = $.connection.commentHub;
commentHub.client.send = function (content) {
$("#comments-list").append("<li>" + content + "</li>");
};
$.connection.hub.start().done(function () {
commentHub.server.register(entryId);
$("#add-comment").click(function () {
commentHub.server.addComment(entryId, $("#content").val());
});
});
});
</script>
}
But it does not work if I move the final script out to a .js file. Any ideas?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow