SignalR in Asp.net MVC 3: hub is undefined - asp.net-mvc-3

I'm a newbie in SignalR. I'm trying to do this Progress Bar example.
I can't download and install the packages via NuGet, cause there is a proxy in my work that denies the access. So I include de DLLs and the scripts in project by myself.
My view code is below:
<h2>#ViewBag.Message</h2>
<input type="button" id="bookButton" value="Book flight" />
<br />
<b>Status:</b> <span id="msg"></span>
<hr />
<input type="button" id="percButton" value="Process pending emails" />
<div id="bar" style="border: #000 1px solid; width: 300px;">
</div>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/gauge-bar.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.6.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.signalr.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/signalr/hubs")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/simple-gauge-bar.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var bookingHub = $.connection.bookingHub;
$("#percButton").click(function () {
bookingHub.processPendingEmails();
});
$("#bookButton").click(function () {
bookingHub.bookFlight("fco", "jfk");
});
bookinghub.updategaugebar = function (perc) {
$("#bar").html(gaugebar.generate(perc));
};
bookinghub.displaymessage = function (message) {
$("#msg").html(message);
};
$.connection.hub.start();
});
</script>
My Hub code:
public class BookingHub : Hub
{
public void Send(String message)
{
// Call the addMessage method on all clients.
Clients.displayMessage(message);
}
public void BookFlight(String from, String to)
{
// Book first leg
Clients.displayMessage(String.Format("Booking flight: {0}-{1} ...", from, to));
Thread.Sleep(2000);
// Book return
Clients.displayMessage(String.Format("Booking flight: {0}-{1} ...", to, from));
Thread.Sleep(3000);
// Book return
Clients.displayMessage(String.Format("Booking flight: {0}-{1} ...", to, from));
Thread.Sleep(2000);
// Some return value
Clients.displayMessage("Flight booked successfully.");
}
public void ProcessPendingEmails()
{
Clients.updateGaugeBar(10);
Thread.Sleep(2000);
Clients.updateGaugeBar(40);
Thread.Sleep(3000);
Clients.updateGaugeBar(64);
Thread.Sleep(2000);
Clients.updateGaugeBar(77);
Thread.Sleep(2000);
Clients.updateGaugeBar(92);
Thread.Sleep(3000);
Clients.updateGaugeBar(99);
Thread.Sleep(2000);
Clients.updateGaugeBar(100);
}
}
When I ran the project, I noticed the bookingHub is undefined, and I've got null reference errors at this point.
What Am I doing wrong to get this error?
Thanks in advance.

Are you missing the attribute,
[HubName("bookingHub")]
on your BookingHub class? e.g.
[HubName("bookingHub")]
public class BookingHub : Hub
{
public void Send(String message)
{
// Call the addMessage method on all clients.
Clients.displayMessage(message);
}
...

Add Global.asax to your web app and add this to global.ajax.cs:
namespace SampleWebApplication
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}
}
}
See https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs

Related

How do I send data between Ajax and RestController in a SpringBoot?

I want to send the data I received by Ajax to the RestController with POST method and process it there. Then I want to return the list that will be created as a result of the transaction to Ajax.
Controller
#Controller
public class AjaxController {
#GetMapping("/web")
public String web()
{
return "fake";
}
}
Fake.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
$(function () {
$("#ajaxselect1").on('change', function () {
var selectedValue1 = $("select[name=ajaxselect1]").val();
$.ajax({
type : "POST",
url : "/ajaxrest",
data: {item: selectedValue1},
success : function(data){
}
});
});
});
});
</script>
</head>
<body>
<h1>AJAX TESTING</h1>
<div class="row">
<div class="col">
<select name="ajaxselect1" id="ajaxselect1" class="form-control" >
<option value="Chose" selected>Chose</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
</body>
</html>
RestController
#RestController
public class AjaxRest {
#PostMapping("/ajaxrest")
public String testAjaxPost(#RequestParam("item") String item) {
if(item.equals("1")){
List<String> cars = new ArrayList<>();
cars.add("bugatti");
cars.add("ferrari");
cars.add("honda");
cars.add("mercedes");
}
}catch (Exception e){
}
return "hello-world!";
}
}
When I'm not sending any data, Chrome Console returns this information to me:
Chrome Console Error
jquery.min.js:2 POST http://localhost:7070/ajaxrest 404
send # jquery.min.js:2
ajax # jquery.min.js:2
(anonymous) # web:26
dispatch # jquery.min.js:2
y.handle # jquery.min.js:2
ListPicker._handleWindowTouchEnd
POST method does not work. How do I run it with POST method? How do I send data between Ajax and RestController?
What exact AJAX error you are getting ? As your if loop looks good, but this might help,
#RestController
public class AjaxRest {
#PostMapping("/ajaxrest")
public Object testAjaxPost(#RequestBody String item) {
if(item.equals("1")){
//If the incoming data is 1, I want to send this list to Ajax.
List<String> cars = new ArrayList<>();
cars.add("bugatti");
cars.add("ferrari");
cars.add("honda");
cars.add("mercedes");
// Send list of cars
return cars;
}
else{
// Your business logic
return "your_value";
}
}
}

Object not set to instance of object in Azure Emulator Model View

I have an exception caused by a direct copy of another code which follows:
Controller:
public PartialViewResult Pictures()
{
picturesList.Clear();
CloudTable table = _Service.GetCloudTable();
CloudBlobContainer blob = _Service.GetCloudBlobContainer();
TableQuery<PictureEntity> query = new TableQuery<PictureEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "hiltihaningepictures"));
foreach (PictureEntity pic in table.ExecuteQuery(query))
{
picturesList.Add(pic);
}
picturesList.Sort();
return PartialView();
}
View:
#model List<WebRole.Models.PictureEntity>
<script type="text/javascript" src="~/Scripts/jquery.liquid-slider.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.touchSwipe.min.js"></script>
<script type="text/javascript">
$(function () {
$('#main-slider').liquidSlider({
height: '525px',
minHeight: '525px',
dynamicArrows: true,
dynamicArrowsGraphical: true,
autoHeight: false,
continuous: true,
autoSlide: true,
pauseOnHover: true
});
});
/* If you need to access the internal property or methods, use this:
var api = $.data( $('#slider-id')[0], 'liquidSlider');
*/
</script>
<div id="main_liquid" style="display: none;">
#foreach (var item in Model)
{
<div class="liquid-slider" id="main-slider">
<div>
<img src="#item.Url" class="intro_img_group" />
<p>Uppladdad av: #item.Uploader, #item.Timestamp.DateTime</p>
<p>Beskrivning: #item.Description</p>
</div>
</div>
}
The only difference is that the other view, which work just fine and dandy, doesn't contain the Javascript section. Other than that completely identical.
Exception details:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=App_Web_v2igssw5
StackTrace:
at ASP._Page_Views_Home_Pictures_cshtml.Execute() in g:\HiltiHaninge\HiltiHaninge\Views\Home\Pictures.cshtml:line 23
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
It's recommendening me to use keyword new but I dont' know what to do

Dropdown using Ajax

I wrote the below code; when I select India/America in the dropdown related text files with some contents, has to be read and displayed inside a div element, but am getting an error in the line xhr.send()
can anyone explain why??
<html>
<head>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>

Anti Forge Token and Ajax JSON Post Does not Work

I am running MVC3, .Net 4 and VS2010. I have following sample project to illustrate the problem.
My controller code
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
My view and JavaScript code
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
Here I have 2 buttons, the first one triggers form post, the second one triggers Ajax post. The form post works fine, but the Ajax one does not, the server complains A required anti-forgery token was not supplied or was invalid. even though I have included the token in my JSON already.
Any idea what is wrong with my code?
This code works.
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>

Uploadify in MVC3 does not work

Can't get this to do anything. When I click 'Upload File' absolutely nothing happens as well as I don't see any of the flash rendered to the screen. I believe this is somehow related to the jquery, but I am not sure. PLEASE HELP! If someone can mail me a simple VS2010 solution with uploadify working to infinitimods at gmail.com that actually works I'd appreciate even more! Thanks a bunch!
My Layout file:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link type="text/css" rel="Stylesheet" media="screen" href="/Scripts/uploadify/uploadify.css" />
<script type="text/javascript" src="/Scripts/uploadify/swfobject.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery-1.4.2.min.js"></script>
</head>
<body>
#RenderBody()
</body>
</html>
My index file:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<script type="text/javascript">
$(document).ready(function () {
$("#file_upload").uploadify({
'uploader': '~/Scripts/uploadify/uploadify.swf',
'cancelImg': '~/Scripts/uploadify/images/cancel.png',
'buttonText': 'Upload foto',
'script': '/Home/UploadFiles',
'folder': '/Content/upload',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'scriptData': { 'thisGuid': $("input#Id").val() },
'multi': false,
'auto': true,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$("#btnSave").button().click(function (event) {
$('#file_upload').uploadifyUpload();
});
});
</script>
<input id="file_upload" type="file" />
<input type="button" id="btnSave" value="Upload file" />
<input id="Id" name="Id" type="hidden" value="5168e-yada-yada" />
}
My controller:
public class HomeController : Controller
{
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Index()
{
return View("Index");
}
/// <summary>
///
/// </summary>
/// <param name="fileData"></param>
/// <param name="form"></param>
/// <returns></returns>
[HttpPost]
public string UploadFile(HttpPostedFileBase fileData, FormCollection form)
{
return "ok";
}
}
Uploadify requires jQuery. This means that you need to include the jQuery script before the uploadify script. If you had looked in your javascript debugging console you would have seen this error.
So, the layout:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Scripts/uploadify/uploadify.css")" type="text/css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/swfobject.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery-1.4.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js")"></script>
</head>
<body>
#RenderBody()
</body>
</html>
The controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileData, string thisGuid)
{
if (fileData != null && fileData.ContentLength > 0)
{
var appData = Server.MapPath("~/app_data");
var file = Path.Combine(appData, Path.GetFileName(fileData.FileName));
fileData.SaveAs(file);
}
return Json(new { status = true });
}
}
and the view:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': false,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$('form').submit(function () {
$('#file_upload').uploadifySettings('scriptData', { thisGuid: $('#id').val() });
$('#file_upload').uploadifyUpload();
return false;
});
});
</script>
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
<input type="submit" value="Upload file" />
}
And if you want to kick the uploading process when the user selects a photo you could get rid of the form and the submit button and set the auto property to true:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': true,
'scriptData': { thisGuid: $('#id').val() },
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
});
</script>
<h2>Index</h2>
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
Also don't forget to checkout the uploadify documentation to better understand what the different options are used for and also you can see some examples.
You need to work around a bug with asp.net and flash.
This article helped me once: Working around flash cookie bug
Maybe this is a better solution: jquery file upload

Resources