I was using signalR to manage database changes, when it happens I want to update the page to other users so that they see the change. But what I've done so far always loads, here is the code:
INDEX
#section scripts{
<script src="~/Scripts/jquery.signalR-2.4.3.min.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var hubNotify = $.connection.Connection4Hub;
$.connection.hub.start().done(function () {
getAll();
});
hubNotify.client.GetUpdateData = function () {
getAll();
};
});
function getAll() {
var model = $('#dataModel');
$.ajax({
url: '/Manage/GetUpdateData',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html',
success: function(result) { model.empty().append(result); }
});
location.reload();
}
</script>
}
Connect4Hub
public class Connect4Hub : Hub
{
public static void BroadcastData()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<Connect4Hub>();
context.Clients.All.GetUpdateData();
}
}
MANAGE
public ActionResult GetUpdateData()
{
return PartialView("Index", db.Matches.ToList());
}
UPDATE
In the console while running i get this error
Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. .
start jQuery
https://localhost:44398/:216
jQuery 2
mightThrow
process
Related
My goal is:
I am trying to send values into a method of my controller to update the database (which is connected remotely via API).
I have checked several tutorials (How to pass parameters in $ajax POST? for example) but I can not send the data in my controller I have a 500 error that is due to my ajax call.
Could you tell me what to do?
View
$(document).ready(function () {
$.ajax({
url: "http://localhost:44338/Registration/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
Controller
[Authorize]
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.RegisterForm rF)
{
try
{
var test = rF.id;
Ok("success");
}
catch (Exception e)
{
Console.Write(e.Message);
return BadRequest();
}
return View();
}
Model
public class RegisterForm
{
public string id { get; set; }
}
Create Model first now(Standard Way)
Try this and let me know.
public class InfoModel
{
public string id { get; set; }
//Add your model fields here
}
Your Api
[HttpPost]
public async Task<ActionResult> ShowRegistration(InfoModel im)
{
//code
}
Your ajax call test this and then send more data:
$.ajax({
url: "url",
type: 'POST',
data: JSON.stringify({"id": id}),
contentType: 'application/JSON',
success: function (data) { },
error: function () {};
})
Tested Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:62211/Home/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
</script>
</head>
<body>
</body>
</html>
Api
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication5.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.info inf)
{
// Access inf.id
return null;
}
}
}
I have trying sending Ajax request to server in my web application, but it always return me 500 internal server error
following is my code
test.aspx
<script src="assets/plugins/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var postdata = JSON.stringify(
{
"Name": "rakeev",
"Age": "28"
});;
function testjson() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.aspx/GetId",
data: "{json: '" + postdata + "'}",
dataType: "json",
success: function (result) { alert("c"); },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="text" onclick="testjson()" / >
</form>
</body>
test.aspx.cs
namespace testApp
{
public partial class test : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static Int64 GetId(string data)
{
using (JoyRydeAnalysis.Data.joyryde_analyzerEntities context = new JoyRydeAnalysis.Data.joyryde_analyzerEntities())
{
var id = context.tbl_item_list.Where(x => x.TXT_ITEM_NAME == data).Select(x => x.LNG_ITEM_ID).FirstOrDefault();
return id;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Is there any other method used to send AJAX call in Asp.net webApplication ?
I have an ajax POST like this
$(document).ready(function () {
var pcontent = document.body.innerHTML;
var url = new URI();
$.ajax({
url: url,
type: "POST",
data: { "pcontent": pcontent },
success: function (data) {
alert($(data).find(".right-panel").html());
},
complete: function () {
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong");
}
}
});
return false;
});
I am little confused how i could retrieve data (pcontent) that i post here in my code behind.actually in a specific class file i need to implement this logic .
You have to create a controller action:
public class HomeController: {
// model
public class PDocument {
public string pcontent {get;set;}
}
[HttpPost]
public ActionResult SaveDocument(PDocument pcontent){
// do something
return new JsonResult() { Data = new { Success = true } };
}
}
JS:
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: { "pcontent": pcontent}
...});
Note:
You don't need to create a model on server if set
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: pcontent
});
// server side
public ActionResult SaveDocument(string pcontent){
// do some thing
}
For security reason, your html must be encoded before calling ajax
In case you new to mvc, then this is a good way to start: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller
In my controller:
public ActionResult ViewPage()
{
Obj object = new Obj();
object.id = 3;
var JsonItem = Model.getItem(object);
return Json(JsonRfc, JsonRequestBehavior.AllowGet);
}
Client-side
$(document).ready(function () {
$.getJSON({
url: 'ViewPage',
function(data) {
console.log(data);
}
});
});
I'm not logging anything in my console (console.log(data) returns nothing). What am I missing here? When I click on the ActionLink ViewPage, it should go into the model and do some stuff. After I want to get it from the client-side to generate a list view.
Perhaps you are missing something.
Try
$(document).ready(function () {
$.getJSON({
url: 'ViewPage',
success: function(data) {
console.log(data);
}
});
});
I have this string variable call "status" which is updated by a serial port connection I've made. the "status" show's if u are connected to the serial port or not.
I've made a simple 2 buttons view. one opens the connection and the other close it.
i want to be able to auto update the status of the connection inside the view.
i guess i need to use some kind of timer which shows the string inside "status" every given time, but i have no clue on how to do it..
This is my HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult CheckStatus()
{
return Json(new { status = "active" });
}
}
and this is my view:
<script type="text/javascript">
$(function() {
// poll every 5 seconds
setInterval('checkStatus()', 5000);
}
function checkStatus() {
$.ajax({
url: 'Home/CheckStatus',
type: 'POST',
dataType: 'json',
success: function(xhr_data) {
if(xhr_data.status == 'active') {
// this would just disable the "Open" button
$('#btnOpen').attr('disabled', 'disabled');
}
}
});
}
I'm going to assume you can use jQuery, and that you have a Controller action that looks like this:
[HttpPost]
public class StatusController : Controller
{
public JsonResult CheckStatus()
{
return Json(new { status = "active" });
}
}
Then, in your view add the following script
<script type="text/javascript">
$(function() {
// poll every 5 seconds
setInterval('checkStatus()', 5000);
}
function checkStatus() {
$.ajax({
url: 'Status/CheckStatus',
type: 'POST',
dataType: 'json',
success: function(xhr_data) {
if(xhr_data.status == 'active') {
// this would just disable the "Open" button
$('#btnOpen').attr('disabled', 'disabled');
}
}
});
}
</script>