how to send hidden field to controller via model binding - javascript

Hope one kindly can help me, it may be a simple question but frustrated me as there is no fix for it,
I want to pass value from a hidden field to controller via model binding,
no matter what approach I use, just passing the value from view to controller via model can work for me,
this is my slider range
<label for="amount">دامنه قیمت:</label>
<div id="connect" class="noUi-target noUi-ltr noUi-horizontal noUi-background">
</div>
this is the hidden field,
<input type="hidden" name="MinPrice" value="#Model.MinPrice" id="MinPrice" />
<input type="hidden" name="MaxPrice" value="#Model.MaxPrice" id="MaxPrice" />
< script >
var connectSlider = document.getElementById('connect');
noUiSlider.create(connectSlider, {
start: [40000, 800000],
connect: true,
range: {
'min': 0,
'max': 2000000
}
}); < /script>
<script>
var connectBar = document.createElement('div'),
connectBase = connectSlider.querySelector('.noUi-base');
/ / Give the bar a class
for styling and add it to the slider.
connectBar.className += 'connect';
connectBase.appendChild(connectBar);
connectSlider.noUiSlider.on('update', function(values, handle, a, b, handlePositions) {
var offset = handlePositions[handle];
// Right offset is 100% - left offset
if (handle === 1) {
offset = 100 - offset;
}
// Pick left for the first handle, right for the second.
connectBar.style[handle ? 'right' : 'left'] = offset + '%';
}); < /script>
<script>
var valueInput = document.getElementById('MinPrice'),
valueSpan = document.getElementById('MaxPrice');
/ / When the slider value changes, update the input and span
connectSlider.noUiSlider.on('update', function(values, handle) {
if (handle) {
valueInput.value = values[handle];
} else {
valueSpan.innerHTML = values[handle];
}
});
// When the input changes, set the slider value
valueInput.addEventListener('change', function() {
connectSlider.noUiSlider.set([null, this.value]);
});
< /script>
this is my JS that fill the hidden field, these two fields are filled correctly, but dont send data to controller via model,
thank you all pal,
Updated
this is my model:
public class SearchModel
{
public string Devision { get; set; }
public string Gender { get; set; }
public int? MinPrice { get; set; }
public int? MaxPrice { get; set; }
public string Brand { get; set; }
public string Sport { get; set; }
public string Size { get; set; }
public string ProductGroup { get; set; }
public List<tblSiteItem> Result { get; set; }
public List<tblSiteItem> Sales { get; set; }
public List<string> Devisions { get; set; }
public List<string> Genders { get; set; }
public List<string> Brands { get; set; }
public List<string> Sports { get; set; }
public List<string> Sizes { get; set; }
public List<string> ProductGroups { get; set; }
public List<tblSiteCart> CartItems { get; set; }
public int PageNo { get; set; }
public int Barcode { get; set; }
}
As I said the value is filled correctly so I do not need code to make it corrected, Just not bind the hdnValue to the field in my model.
I mean MinPrice and MaxPrice.
Edited
I am not allowed to upload images sadly, If I were everything was pretty obvious to look at,
any way, I explain the detail:
when I change the slideBar, my JS fires and values change,
when I click the search button all the fields in my model is field except for these two field , I mean MinPrice and MaxPrice
result shows an empty page , again my Js keep fired then come back to the default values,
in the last try I changed the hidden field to type="text"
and saw that when I change the slidebar the value is in my text box but not binded to my view model when touch search button.
I am sure there is something wrong with my viewmodel, but How I can understand what is incorrect :( please kindly look at my code

The names of your inputs are incorrect. You should remove the Model. part from it. If you used HtmlHelper.HiddenFor, you'd get the following:
<input type="hidden" name="MaxPrice" value="#Model.MaxPrice" id="MaxPrice" />
This way, the inputs will get submitted to your model correctly.
Have a look at this answer.

Use this code for get the value:
var userRole = "";
userRole = $("#hdnVal").val();
alert(userRole);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hdnVal" value="#Model.MinPrice" />

Follow this.
On .cshtml Page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hdnVal" value="#Model.MinPrice" />
<input type="button" name="Submit" value="Submit" id="btnSubmit" class="btn btn-primary" />
Js
var userRole = "";
userRole = $("#hdnVal").val();
alert(userRole);
$('#btnSubmit').click(function() {
var formData = new FormData();
formData.append("userRole ", userRole);
$.ajax({
type: "POST",
url: "/Controller/YourAction/",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(result) {
if (result.Message == "success") {
alert("Success");
}
}
});
}
C# Code
public JsonResult YourAction()
{
string Role = Request.Form["userRole "];
//You can get the value of role
}

I had the same problem and after several test I found the solution sending values via ajax but building the data for the request in a string JSON format, where the hidden fields, are written without single quotes and the other fields with single quotes. Below is shown the example. I hope that this variant help you.
JavaScript code to send data to controller
$("#saveSearchModel").on("click", function (e) {
e.preventDefault();
// Variables for fields values
var devision = $("#Devision").val();
var gender = $("#Gender").val();
var minPrice = $("#MinPrice").val();
var maxPrice = $("#MaxPrice").val();
var brand = $("#Brand").val();
/*
Get the other fields...
*/
// Data for pass to controller via ajax
var data1 = "{'Devision':'" + devision + "','Gender':'" + gender + "',MinPrice:" + minPrice + ",MaxPrice:" + maxPrice + ",'Brand':'" + brand + /*Add the other fields...*/ + "'}";
$.ajax({
url: '/Controller/Action1',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: data1,
success: function (result) {
// Do something
}
});
});
Code in controller to receive data
[HttpPost]
public void Action1(SearchModel model)
{
// Gets the values of model
string devision = model.Devision;
string gender = model.Gender;
int? minPrice = model.MinPrice;
int? maxPrice = model.MaxPrice;
string brand = model.Brand;
/*
Gets the others values of model...
*/
}

Related

Sending PDF from jsPDF to controller via ajax

Guys how can I send the jsPDF file to the controller while also including the model. I believe I have to change the ajax data: piece, This however is eluding me. Any help would be appreciated.
Model:
public class PartialReportModel
{
public List<ShiftReportDetail> ReportDetails { get; set; }
public ShiftReport Report { get; set; }
public byte[] testingImg { get; set; }
public IFormFile pdf { get; set; }
public List<UserListsForSignatures> ListOfNames { get; set; }
public List<ProductCodes> ProductsList { get; set; }
public List<EquipList> Equipment { get; set; }
public List<CodeTable> CodeList { get; set; }
}
Controller:
[HttpPost]
public async Task<IActionResult> EditReport(PartialReportModel model,IFormFile Test)
{
// do something else here with pdf and model
return Json(1);
}
JS:
$(document).on("click", "#SubmitReportEdits", function () {
var pdf;
html2canvas(document.querySelector("#mod1")).then(canvas => {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm', 'a4', true);
var width = doc.internal.pageSize.width;
var height = doc.internal.pageSize.height;
doc.addImage(imgData, 'PNG', 10, 10, width - 20, height - 10);
pdf = doc.output('blob');
//doc.save('test.pdf');
});
// ajax the thing
$.ajax({
type: "POST",
url: $("#EditReportForm").attr("action"),
data: $("#EditReportForm").serialize() + "&Test="+pdf,
success: function () {
// close the modal
// reload the table
$('#ReviewReport').modal('toggle');
$('#NotificationDiv').append( // change
"<div class='alert alert-success alert-dismissible fade show' role='alert'>
" + "Report has been edited. Thank you." +
"<button type='button' class='close' data-dismiss='alert' aria-
label='Close'>" + "<span aria-hidden='true'>×</span>" + "</button>" + "
</div>"
);
}
});
});
Currently I can see my model stuff but the pdf side is null.
Because we all have deadlines :/, I am going to use this method to work this for now until a better answer comes along.
First is to convert the file to a base64 string, Then set that to a value inside the form. Have a hidden input to receive the value. This case string pdf. Then pass it along the ajax. We now see the value in the controller side. Also have to use jpeg as PNG was too large a file and was getting 413 server errors. Code_debt++
model:
public string pdf { get; set; }
HTML5:
<input asp-for="pdf" hidden/>
Javascript:
$(document).on("click", "#SubmitReportEdits", function () {
html2canvas(document.querySelector("#mod1")).then(canvas => {
var imgData = canvas.toDataURL(
'image/jpeg');
var doc = new jsPDF('p', 'mm', 'a4', true);
var width = doc.internal.pageSize.width;
var height = doc.internal.pageSize.height;
doc.addImage(imgData, 'jpeg', 10, 10, width - 20, height - 10);
var pdf = doc.output('datauristring').slice(28); // wipe first28chars
//saving the base64
$('#pdf').val((pdf));
// ajax the thing
$.ajax({
type: "POST",
url: $("#EditReportForm").attr("action"),
data: $("#EditReportForm").serialize(),
success: function () {
// close the modal
// reload the table
$('#ReviewReport').modal('toggle');
$('#NotificationDiv').append( // change
"<div class='alert alert-success alert-dismissible fade show' role='alert'> " + "Report has been edited. Thank you." +
"<button type='button' class='close' data-dismiss='alert' aria-label='Close'>" + "<span aria-hidden='true'>×</span>" + "</button>" + "</div>"
);
}
});
});
});
Controller Side:

Passing Values from Checkboxes from View to Controller

I am having trouble passing data from my view to my controller. I am using checkboxes. For my view, I created a class that takes in all my checkboxes (Mon-Fri) and putting them into a list (so I can use the data someplace else). My problem is that when I debug and click the checkboxes on the website, the code does not change whether I click the checkbox or not, so my code doesn't recognize the checkbox data
I'm not sure if I have implemented the View incorrectly but any help to the right direction would be appreciated !
ViewModel:
public List<cDay> _cDays = new List <cDay>();
public List<cDay> cDays
{
get {return _cDays;}
set {_cDays = value;}
}
public class cDay
{
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
}
CSHtml file:
#Html.Label("M")
#Html.CheckBox("Monday", false, new { #class = "availability" })
// this is basically the same code for Tuesday-Friday as well.
'<label for="M">M</label> +
'<input class="availability" id="Monday" name="Monday" type="checkbox" value="true">' +
'input name="Monday" type="hidden" value="false">'
// this is basically the same code for Tuesday-Friday, but the "name" corresponds to each day
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string inputValue, Model viewModel)
{
if(ModelState.IsValid)
//
}
Consider to use the following data model:
public class DaysViewModel
{
public List<CDay> Days { get; set; } = new List<CDay>();
}
public class CDay
{
public CDay()
{
Name = string.Empty;
Selected = false;
}
public CDay(string name)
{
Name = name;
Selected = false;
}
[Required]
public string Name { get; set; }
[Required]
public bool Selected { get; set; }
}
Then you can use the default ASP.NET MVC data binding without a JS support:
#model Models.DaysViewModel
#using (Html.BeginForm("Edit", "Home"))
{
#Html.AntiForgeryToken()
for(int i=0; i < Model.Days.Count; i++)
{
<div class="form-group row">
#Html.CheckBox("Days[" + i + "].Selected", Model.Days[i].Selected)
#Html.Hidden("Days[" + i + "].Name", Model.Days[i].Name)
<span>#Model.Days[i].Name </span>
</div>
}
<input type="submit" value="Save" />
}
And on the server side:
public ActionResult Edit()
{
var model = new DaysViewModel();
model.Days.AddRange( new List<CDay> {
new CDay("Monday"),
new CDay("Tuesday"),
new CDay("Wednesday"),
new CDay("Thursday"),
new CDay("Friday")
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(List<CDay> days)
{
if(ModelState.IsValid)
{
// ... you_code here
}
var model = new DaysViewModel() { Days = days };
return View(model);
}
Test screen shots
The view:
On the controller side:
You can do it using jQuery
Add a button bellow your checkboxes
<input type="button" value="Your_Value" class="btn btn-default" />
When click on a button create a post request and sends checked status via querystring
$(document).ready(function () {
$("input[type=button]").click(function () {
var queryString = 'Monday=' + $("input[name=Monday]").is(":checked") + '&Tuesday=' + $("input[name=Tuesday]").is(":checked") + '&Wednesday=' + $("input[name=Wednesday]").is(":checked") + '&Thursday=' + $("input[name=Thursday]").is(":checked") + '&Friday=' + $("input[name=Friday]").is(":checked");
$.ajax({
type: "Post",
url: "/Home/Edit?" + queryString,
success: function (data) {
},
error: function (data) {
}
});
});
});
And inside controller create Edit Post Method like this
[HttpPost]
public ActionResult checkboxespost(string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
{
...
}

Ajax POST data not appearing in modal

I have a table that's populated by JSON data. In the last column you can open up a modal that corresponds to each row and you can add a comment in an input box---doing so will update that modal. In other words, table rows that have no comments have an empty modal and rows with at least one comment should appear in the modal that they correspond with.
In my backend manager (SQL Server Management Studio) I can see that the comments are showing up there, but they're not appearing in the modals.
I can't tell if the problem is coming from the JavaScript side (the view) or from the model, or from elsewhere.
The addition of the DocBudgetId is relatively new. Before that, the review/comment data was tied to the DocNumber and the info was appearing in the modals. I suspect that I have to make an adjustment/change to the DocBudgetId but I'm not sure how.
Modal screenshot: https://i.stack.imgur.com/Vqd4o.png The DocNumber appears on the top left. Comments have been made to the row that this modal belongs to but they're not appearing in the modal table.
Model:
public class ReviewRow
{
public Guid DocBudgetId { get; set; }
public string DocNumber { get; set; }
public string ReviewBy { get; set; }
public string ReviewOn { get; set; }
public string ReviewComment { get; set; }
}
View:
<div class="modal-body">
<div id="review"></div>
<table>
<tr>
<td>
#Html.LabelFor(x => Model.ReviewComment)<br />
#Html.TextAreaFor(x => x.ReviewComment, new { style = "width: 200px; " })<br />
#Html.HiddenFor(x => x.DocUnderReview, new { id = "txtDocUnderReview" })
<input type="submit" value="#BB360.Models.BudgetReportingViewModel.Buttons.Review" name="#Html.NameFor(x => x.SubmitButton)" id="SubmitButton" class="btn btn-secondary" />
</td>
</tr>
</table>
// --- other code --- //
function ShowReviewModal(DocBudgetId, DocNumber) {
$("#txtDocUnderReview").val(DocNumber);
console.log(DocNumber)
$.ajax({
type: "POST",
url: "/Doc/GetDocUnderReviewDetails",
data: "docNumber=" + DocNumber + "&docBudgetId=" + DocBudgetId,
timeout: 5000,
success: function(data) {
console.log(data); // ------------- empty array
// write out the modal table
var tBody = $("#tblExpenseDeductionDetails tbody");
tBody.empty();
s = "";
for (x = 0; x < data.length; x++) {
let ReviewBy = data[x].ReviewBy,
ReviewOn = data[x].ReviewOn,
ReviewComment = data[x].ReviewComment;
s = s + "<tr>";
s = s + "<td>" + ReviewBy + "</td>";
s = s + "<td>" + ReviewOn + "</td>";
s = s + "<td title='" + ReviewComment.replace(/'/g, '') + "' style='max-width:550px;word-wrap: break-word;'>" + stringTruncate(ReviewComment, 65) + "</td>";
s = s + "</tr>";
}
$("#modalDocName").text(DocNumber);
tBody[0].innerHTML = s;
$("#ReviewModal").modal();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
$("#ReviewModal").modal();
}
Controller
public ActionResult BudgetReporting(BudgetReportingViewModel model)
{
Common.GetDbExecutor().QueryNonQuery(Sql.InsertDocUnderReview, new {
model.DocBudgetId,
DocNumber = model.DocUnderReview, // D is uppercase
ReviewBy = Common.GetUserName(),
ReviewComment = model.ReviewComment,
}, 30).ToString();
PopulateBudgetReportingDetail(model);
return View(model);
}
public ActionResult GetDocUnderReviewDetails(Guid docBudgetId) // camelCase //
{
var data = Common.GetKKDbExecutor().Query<BudgetReportingViewModel.ReviewRow>(Sql.GetDocUnderReviewDetails, new {
docBudgetId
}).ToList();
return Json(data);
}
Sql file
namespace BB360
{
public partial class Sql
{
public const string GetDocUnderReviewDetails = #"
select
DocBudgetId,
DocNumber,
ReviewBy,
convert(varchar, ReviewOn, 101) as ReviewOn,
isnull(ReviewComment, '') as ReviewComment
from DocBudgetReview
where DocBudgetId = #DocBudgetId
order by ReviewOn desc
";
}
}
The issue here is your "GetDocUnderReviewDetails" action accepts GET request and you're sending a post request to it. You just need to change the ajax request type to GET.
type: "GET",
url: "/Doc/GetDocUnderReviewDetails",
Another thing i noticed is that, you're sending the docNumber also in the request which your action doesn't require. Even though that won't cause any issue but you don't need to send that in ajax
Update: I did some tinkering and got the table data to show.
In the stored procedure (GetDocUnderReviewDetails.cs) I commented out the line where DocBudgetId = #DocBudgetId and added where DocNumber = #DocNumber. I noticed that if I just commented out where DBI = then it showed all of the comments made for every modal, which was an issue I was dealing with earlier.
So now, my stored procedure looks like this:
namespace BB360
{
public partial class Sql
{
public const string GetDocUnderReviewDetails = #"
select
DocBudgetId,
DocNumber,
ReviewBy,
convert(varchar, ReviewOn, 101) as ReviewOn,
isnull(ReviewComment, '') as ReviewComment
from DocBudgetReview
--where DocBudgetId = #DocBudgetId
where DocNumber = #DocNumber
order by ReviewOn desc
";
}
}
I also added string docNumber to the Controller:
public ActionResult GetDocUnderReviewDetails(Guid docBudgetId, string docNumber)
{
var data = Common.GetBBDbExecutor().Query<BudgetReportingViewModel.ReviewRow>(Sql.GetDocUnderReviewDetails, new {
docBudgetId,
docNumber
}).ToList();
return Json(data);
}

Displaying data from a query using a drop down list selection mvc

I am sort of lost on the coding part of this problem. I have a MVC application, and I am trying to populate a queries Where clause as the selected value from my drop down list. Also, I am populating the drop down list from a query in the database. For example:
SELECT db.ID FROM Database db where ID = 1232
Instead of that, I want to do something like this...
SELECT db.ID FROM Database db where ID = "SelectedValue from Dropdownlist"
Model Class:
public string ID {get; set;}
public string Summary{get; set;}
public int Estimate {get; set;}
public List<Hello> getIDs()
{
var que = (from wre in db.Table
select new Hello{
ID = wre.ID
}).toList();
}
Controller class:
public ActionResult Index(string? IDParam)
{
var model = test.getStuff();
var que = (from wre in db.View
where wre.ID == IDParam //Operator '==' cannot be applied to operands of type 'string' and 'string?'
select new Hello
{
ID = wre.ID
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
if (IDParam!= null & IDParam.HasValue)
{
model = model.Where(x => x.ID == IDParam); //Operator '==' cannot be applied to operands of type 'string' and 'string?'
}
return View(model);
}
View Class:
#Html.DropDownList("ID", ViewBag.Releases as SelectList, "ID", new {#id="rel" })
<table>
<th>#Html.DisplayNameFor(model => model.ID)</th>
<th>#Html.DisplayNameFor(model => model.Summary)</th>
<th>#Html.DisplayNameFor(model => model.Estimate)</th>
</table>
<script>
$("#rel").change(function () {
var selectedId = this.val();
location.href = '#Url.Action("Index", "SampleController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
</script>
This works perfectly fine, but now, I am lost on the coding aspect of it. I can see the alert every time I change the ID from the drop down list. However, there is no change in the data being displayed (I know I am missing a lot). If anyone can help me out here, that would be great, thank you!
1) Try adding where clause in Linq
where wre.ID == IDParam
2) Change que to instance of your class and get firstOrDefault instead of List
3) Try passing instance of your class as a model in view
return View(test);
1- You need to get changed Id as below :
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
});
2- If you want to reload your page then you need to set a parametre to your [HttpGet] Method :
public ActionResult Index(int? selectedId) // selectedId
{
var que = (from wre in db.View
select new Hello
{
ID = IDParam
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
ViewBag.Releases = new SelectList(test.getIDs(), "", "ID");
var model = test.getStuff();
if(selectedId!=null && selectedId.HasValue)
{
// do some stuff with your selectedId
// if working method is test.getStuff(), then maybe you can use like code below:
model = model.Where(x=> x.Id==selectedId);
}
return View(model);
}
and in your View:
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
location.href = '#Url.Action("Index", "YourController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
3- If you dont want to reload page then you need to use Ajaxrequest, You must create a new method for get data by selectedId,
// Your view.
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
$.ajax({
method: "POST",
url: "'#Url.Action("GetDataBySelectedId","YourController")'",
data: { selectedId: selectedId }
})
.done(function( data) {
// Delete your table, and fill table with your data with jquery.
});
});
// your Controller:
[HttpPost]
public JsonResult GetDataBySelectedId(int? selectedId)
{
// Do some stuff for get your data.
var data = yourData.Where(x=> x.Id = selectedId.Value);
return Json(data);
}

Unable to update webpage with database notifications realtime with SignalR

I am working on a web application developed using Asp.Net MVC which on which I have a page on which data gets updated at realtime whenever data is modified on the database. I have some source on line and tried to implement this feature but it resulted in huge invalid data on the webpage.
I am using SQL dependency and SignalR to achieve this as follows
In Global.asax, I have the following
protected void Application_Start()
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
protected void Application_End()
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
and in Models section I have the following classes
public class JobInfo
{
public int JobID { get; set; }
public string Name { get; set; }
public DateTime LastExecutionDate { get; set; }
public string Status { get; set; }
}
public class JobInfoRepository
{
public IEnumerable<JobInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [JobID],[Name],[LastExecutionDate],[Status]
FROM [dbo].[JobInfo]", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo(){
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3) }).ToList();
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
JobHub.Show();
}
}
I have created a SignalR Hub class as follows which has the Show() function used in the above class
using Microsoft.AspNet.SignalR.Hubs;
public class JobHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
context.Clients.All.displayStatus();
}
}
And I have the controller in which I am calling GetData() method defined in the JobInfoRepository class
public class JobInfoController : Controller
{
// GET: /JobInfo/
JobInfoRepository objRepo = new JobInfoRepository();
public IEnumerable<JobInfo> Get()
{
return objRepo.GetData();
}
}
I have created an Action named JobInfo in HomeController and returned the following view
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JobStatus</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div>
<table id="tblJobInfo" class="clientTable" style="text-align:center;margin-left:10px"></table>
</div>
</body>
</html>
#section scripts {
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="~/App/JobInfo.js"></script>
}
to retrieve the data and supply it to tblJobInfo id in the above html, a java script function is used
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../JobInfo/',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Status</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Status + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
As in the demo I found it to be working fine but when I go to http://localhost:57044/Home/JobInfo/ I get invalid data on the page besides not getting the realtime notifications as in the following image
reference to the source I found online is http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency

Categories

Resources