updating a variable in an ASP.NET MVC view - c#

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>

Related

SignalR notification reload always the pyhjyjage

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

How to send one value after successful ajax post request to a page redirect

I am learning ASP.net MVC - 5 and I am stuck at one problem. So I need to open a URL after successful Ajax Post Request. But I also want to pass one value to the new URL's Controller Action. Below is what I have till now.
AJAX CALL
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
if (result == true) {
int TEMPVAR = 2;
DisplayError('Save Successful', 'Success', function () {
window.location.href = '/Settings/Customize/'; });
},
error: function (error) {
}
});
Controller Action
[AuthorizeSettings]
public ActionResult Customize()
{
//I want to be able to access TEMPVAR value here
// code removed for brevity
return View(configData);
}
Question: How to pass the TEMPVAR data to the Customize Action
Points:
I know there are some ways to pass data. TempData,Viewbag,SessionVariable, Embedding the TEMP value in URL Request, Anonymous Objects, ViewData, Static variable for the class, Global Variable, JSON. But I am totally confused how to pass data. I am newbiew please guide me here.
EDIT:
AJAX CALL
$.ajax({
url: URL,
type: 'POST',
data: data,
success: function (result) {
if (result == true) {
int TEMPVAR = 2;
DisplayError('Save Successful', 'Success', function () {
window.location.href = '/Settings/Customize/'; });
TEMPDATA["value"] = TEMPVAR;
},
error: function (error) {
}
});
Based on comments, you want to send data from SaveStyles to Customize. If so, you can use TempData -
public class PersistController : Controller
{
[HttpPost]
public ActionResult SaveStyles()
{
TempData["Status"] = true;
TempData["Val"] = 4;
return Json(true);
}
}
public class SettingsController : Controller
{
public ActionResult Customize()
{
bool status = Convert.ToBoolean(TempData["Status"]);
int val = Convert.ToInt32(TempData["Val"]);
return View();
}
}

Call Controller Method using Ajax request

please your help to call a method from controller using ajax request, below is my code, but error had returned says that the source of controller cannot be found.
here is my ajax code
function GetServices() {
var e = document.getElementById("catagories");
var strUser = e.options[e.selectedIndex].value;
var id = e.options[e.selectedIndex].id;
$.ajax({
url: "~/VasController/ExecuteVas/",
//url: '<%= Url.Action("GetServices", "Vas") %>',
type: 'POST',
contentType: 'application/json',
data: {"id": id},
success: function (result) {
alert(result);
}
});
}
and here is my controller method
[WebMethod]
public static string GetServices(string id)
{
return id;
}
kindly advice, i am still beginner in c# and MVC
in your controller file
public class YourControllerNameController : Controller
{
[HttpPost]
public ActionResult Dosomething(int? id)
{
//your code
return View();
}
}
then in your view
$.post('#Url.Action("Dosomething","YourControllerName")', { id: id }, function (data) {
});
You have to do the following:
1- Decorate the Action method with [HttpPost] tag
2- Remove the word 'controller' for the Ajax URL it would be 'url: "~/Vas/ExecuteVas/"
3- if 1 and 2 did not work,Try putting the Ajax URL without ~/

How to pass an object to a MVC controller via Jquery Ajax Get

I am new to jquery and I can't resolve the following problem : I want to pass an object to one of the controllers in my mvc application. Here is what I got so far:
function enterPressed() {
$(function () {
$('#textBox').keypress(function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
doSomethingElse(textBox.value)
}
});
});
}
function doSomethingElse(p) {
$.ajax({
type: 'GET',
data: {string: p},
url: '"Control/AddControl/Index"',
success: function (data) { alert(p) },
error: function (errorData) { alert("fail") }
});
return true;
But every time when I press enter I end up with the fail. My controller is found in ~/Controllers/Control/AddControl. Do any of you see the problem ?
My C# code:
public class AddControlController : Controller
{
//
// GET: /AddControl/
public ActionResult Index(string control)
{
return RedirectToAction("ShowControl");
}
}
You should change value name to control, as action expected. Also you can use #Url.Action() helper for setting url param.
$.ajax({
type: 'GET',
data: { control : p},
url: '#Url.Action("Index","AddControl")',
success: function (data) { alert(p) },
error: function (errorData) { alert("fail") }
});
Finally, your action can't return redirect action with ajax response.
If you want to make redirect after successful response, you can make it in client side.
There are a few problems:
1-you are using a wrong url. The correct url is '/AddControl/Index'.
2-Your code in your controller won't work, since you are using ajax. You should return Json and handle the redirect in the client side.
3-You should allow GET through ajax:
public ActionResult Index()
{
return Json("Ok", JsonRequestBehavior.AllowGet);
}
You might want to just POST in stead of GET.
function doSomethingElse(p) {
$.post(
'#Url.Action("Index", "AddControl")',
{
control: p
},
function (data) {
alert(data);
}
);
}
You should decorate your controller action with the HttpPost attribute:
[HttpPost]
public ActionResult Index(string control)
{
return Json("I received this: " + control);
}

Retrieving data from Ajax POST in asp.net

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

Categories

Resources