SignalR client script runs only in index page - asp.net-mvc-4

I'm developing an MVC 4 web application and using signalR library to make a real time notification system.
I have a working script that I use in master page called _Layout.cshtml.
here's the script in _Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="~/signalr/hubs"></script>
</head>
<body >
<header dir="rtl">
<table align="center" cellpadding="0" cellspacing="0" style="width:100%;">
<tr>
<td style="width:30%; height:40px;" valign="top"><img src="~/Images/header_logo3.png" /></td>
<td style="width: 40%; height: 40px; " valign="top"> <a href='#Url.Action("Index","Home")'><img class="header_logo" src='#Url.Content("~/Images/header_logo2.png")' /></a></td>
<td style="width: 30%; height: 40px; " valign="top" ><img src="~/Images/header_logo4.png" /></td>
</tr>
</table>
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
</header>
<div id="wrapper" dir="rtl">
<div id="Smenu" class="visible">
#{Html.RenderAction("Menu", "SettingsMenu", new { id = "nir"});}
</div>
#RenderSection("JavaScript", false)
<section>
#RenderBody()
</section>
</div>
<footer></footer>
</body>
</html>
the Hub class:
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace HaifanetMobile.Hubs
{
public class NotificationHub : Hub
{
public void SendMessage(string msg)
{
Clients.All.sendMessage(msg);
}
}
}
Everything goes ok and I see the massage method called from the hub class in my page, except that
this script is running only on the index.cshtml (startup page) and not in all the web pages in the project or in a specific one of them. e.g not working and the script is the same as you can see:
#model schoolnetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<span id="mySpanTag"></span>
<script type="text/javascript">
//var notificationHub = $.connection.notificationHub;
$(function () {
//Create Hub on Air
var chat = $.connection.notificationHub;
//Messages
$messages = $("#mySpanTag");
//Client Side Method To Access From Server Side Method
chat.client.sendMessage = function (msg) {
$messages.html(msg);
}
$.connection.hub.start(function () {
chat.server.sendMessage("Hello World!");
});
});
</script>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>username: #Model.UserName</li>
<li>schoolname: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>need to login</h4>
}
Update: I placed the script only if detail.cshtml. Looks like
there is a problem in this line
var chat = $.connection.notificationHub;
as only the first alert("hi") pops up and not the second...
#model HaifanetMobile.Models.UserModel
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts
{
<script type="text/javascript">
$(function () {
//Create Hub on Air
alert("hi");
var chat = $.connection.notificationHub;
alert("hi1");
//Messages
$messages = $("#messages");
alert("hi2");
//Client Side Method To Access From Server Side Method
chat.client.addMessage = function (frm, msg) {
$messages.append("<br /><b>" + frm + ":</b>" + msg);
}
alert("hi3");
$("#txtMsg").keypress(function (e) {
//when enter
if (e.which == 13) {
alert("hi4");
//get value of input
var input = $(this).val();
//send message to "Server Side Method"
chat.server.sendMessage("#Session.SessionID", input);
//Reset TextBox
$(this).val("");
}
});
//Hub Starting
$.connection.hub.start();
});
</script>
}
<div>Your ID: #Session.SessionID</div>
<input type="text" id="txtMsg" />
<div id="messages">
</div>
<h2>Index</h2>
<span id="mySpanTag"></span>
<br /><br />
#if (Request.IsAuthenticated) {
<h4>user profile: #Model.UserName</h4>
if (User.Identity.Name == #Model.UserName)
{
<br />
<ul style="list-style-type: none;">
<li>first name: #Model.FirstName;</li>
<li>user name: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
else
{
<br />
<ul style="list-style-type: none;">
<li>username: #Model.UserName</li>
<li>school: #Model.SchoolName</li>
<li>role: #Model.Role</li>
</ul>
}
}
else
{
<h4>Please login</h4>
}

Related

Blazor RoleClaims Policy Not Working on Api end point

I have application authorizing users based on role claims they owned.
I have following set up
I. Server Side
I have registered policy for startup class
services.AddAuthorization(options =>
{
options.AddPolicy(Permissions.Products.Create, policy => policy.RequireClaim("Permissions", Permissions.Products.Create));
options.AddPolicy(Permissions.Products.Edit, policy => policy.RequireClaim("Permissions", Permissions.Products.Edit));
options.AddPolicy(Permissions.Products.View, policy => policy.RequireClaim("Permissions", Permissions.Products.View));
options.AddPolicy(Permissions.Products.Delete, policy => policy.RequireClaim("Permissions", Permissions.Products.Delete));
});
This is the api controller method.
// GET: api/Products
[HttpGet]
[Authorize (Policy = Permissions.Products.View)]
public async Task<ActionResult<List<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
This is my blazor component
#page "/product-list"
#inject HttpClient client
#inject IJSRuntime js
<h3>Products</h3>
<small>Add as many products as you wish.</small>
<div class="form-group">
<a class="btn btn-success" href="product/create"><i class="oi oi-plus"></i> Create New</a>
</div>
<br>
#if (products == null)
{
<text>Loading...</text>
}
else if (products.Length == 0)
{
<text>No Records Found.</text>
}
else
{
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (Product product in products)
{
<tr>
<td>#product.Id</td>
<td>#product.Name</td>
<td>#product.Type</td>
<td>
<a class="btn btn-success" href="product/edit/#product.Id">Edit</a>
<button class="btn btn-danger" #onclick="#(() => Delete(product.Id))">Delete</button>
</td>
</tr>
}
</tbody>
</table>
}
#code {
Product[] products { get; set; }
protected override async Task OnInitializedAsync()
{
products = await client.GetFromJsonAsync<Product[]>("api/products");
}
async Task Delete(int productId)
{
var product = products.First(x => x.Id == productId);
if (await js.InvokeAsync<bool>("confirm", $"Do you want to delete {product.Name}'s ({product.Id}) Record?"))
{
await client.DeleteAsync($"api/products/{productId}");
await OnInitializedAsync();
}
}
}
Then, I tested by login into superuser which grants all permissions (claims).
I get the user cookies attached to postman.
When I send the request to that controller. it resulted as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>PermissionBlazorApp</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="PermissionBlazorApp.Client.styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>

Bootstrap Alerts in Asp.net Core Razor Pages

How to configure bootstrap alerts in asp.net core razor pages.
<div class="alert alert-success">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
As far as I know, if you want to show the alert, you could try to use jquery to achieve your requirement, you could add class in into the alert div. You could use ajax to call the razor page's onpost method and check the response if the response is true then you could alert success if not you could alert fail message.
More details, you could refer to below example codes:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
#{
Layout = null;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="alert alert-success alert-dismissible fade" id="buttonAlertSuccess">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
<div class="alert alert-success alert-dismissible fade" id="buttonAlertFail">
<strong>False</strong> You failed read this important alert message.
</div>
<button class="btn btn-secondary" id="modalButton" type="submit">Button</button>
#Html.AntiForgeryToken()
<script>
$(function () {
$("#modalButton").click(function () {
$.ajax({
type: "post",
url: "index",
beforeSend: function (xhr) {
xhr.setRequestHeader("CSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
if (response == "True") {
$("#buttonAlertSuccess").addClass('in');
} else {
$("#buttonAlertFail").addClass('in');
}
}
});
})
});
</script>
Post method:
public ActionResult OnPost() {
return new JsonResult("True");
}
Notice:
If you want to use ajax call ,you should set the CSRF-TOKEN settings in the startup.cs ConfigureServices method like below:
services.AddAntiforgery(o => o.HeaderName = "CSRF-TOKEN");
Result:
Please find the complete code and try if it helps
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div id="alert_div" style="margin: 0 0.5%; -webkit-box-shadow: 3px 4px 6px #999;" class="alert-success">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
</body>
</html>

KNOCKOUT:Uncaught (inpromise) referenced error

I am learning knockout and trying out a small example below are the the three files that I have:
index
introduction
introduction
I am using netbeans IDE for the development .
index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script data-main="js/main" src="js/libs/require/require.js" type="text/javascript"></script>
<link href="css/libs/oj/v2.1.0/alta/oj-alta-min.css" rel="stylesheet" type="text/css"/>
<style>
table, th, td {
border: 1px solid black;
padding: 15px;
}
th {
text-align: left;
}
thead{
border-style: double;
font-weight: bold ;
}
tr {
text-align: left;
}
{background-color: #f5f5f5}
</style>
</head>
<body>
<div data-bind="ojModule: {name: 'introduction'}"></div>
</body>
</html>
viewModels - introduction.js
/**
* introduction module
*/
define(['ojs/ojcore', 'knockout',oj,jquery,require
], function (oj, ko) {
/**
* The view model for the main content view template
*/
function introductionContentViewModel() {
var self = this;
self.firstName = ko.observable("Planet");
self.lastName = ko.observable("Earth");
self.fullName = ko.pureComputed(function () {
return this.firstName() + " " + this.lastName();
}, this);
this.fullName= this.firstName() +" " +this.lastName();
this.resetName=function(){
alert("Reset Name!");
this.firstName("James");
this.lastName("Potter");
};
this.capitalizeName=function(){
var curValue=this.lastName();
this.lastName(curValue.toUpperCase());
};
function seatReservation(fname,lname, reservMeals){
this.firstName=fname;
this.lastName=lname;
this.meals = ko.observable(reservMeals);
/* this.formattedPrice=ko.computed(function(){
var price = this.meals.price;
return price ? "$" + price.toFixed(2):"none";
});*/
};
this.mealsAvailable=[{mealName:"SandWich",price:25},
{mealName:"Roti",price:23},
{mealName:"Dal",price:22}];
self.seats = ko.observableArray([
new seatReservation("Steve","Hawkins", this.mealsAvailable[0]),
new seatReservation("Bert","Baltymoore", this.mealsAvailable[1])
]);
//function to add new reservation into the table
this.newReservationRow=function(){
this.seats.push(new seatReservation("","",this.mealsAvailable[0]));
};
}
return introductionContentViewModel;
});
views -introduction.html
<body>
<form>
<div class='liveExample'>
<p> First Name: <span data-bind='text: firstName'/> </p>
<p> Last Name: <span data-bind='text: lastName'/> </p>
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
<button data-bind='click: resetName' >Reset Name </button>
<button data-bind='click: capitalizeName'>Capitalize </button>
<input type='submit' data-bind='click: resetName' value='Reset'/>
</div>
<div class="Reservations">
<h2>Reservations </h2>
<table>
<thead> <tr><td> FirstName </td><td> LastName</td> <td> Meals</td><td> Price</td></tr></thead>
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: firstName"/> </td>
<td><input data-bind="value: lastName"/> </td>
<td><select data-bind="options: meals,optionsText:'mealName'"></select> </td>
<td data-bind="text: meals().price"> </td>
</tr>
</tbody>
</table><br>
<input type="submit" value="New Reservation" label="New Reservation" title="Click to Make a New Reservation" data-bind="click: newReservationRow"/>
</div>
</form>
</body>
I am not getting the desired out put. The desired output is something like this in the below link
http://learn.knockoutjs.com/#/?tutorial=collections
You are mixing self and this a lot in your code. I recommend cleaning that up first and see if things start working for you. Personally, I like to stay with self.xxxx format.
Also, remove the reference to "require" inside of your define block in the introduction.js file. That may be causing some issues. Either way, it's not needed.
Finally, it appears you are doing all of this using Oracle JET. Since the introduction.html is a view that will be used inside of ojModule, you do not need to have the < body> element defined a second time. The introduction.html is going to be a fragment that will take the place of the < div> that you have bound to ojModule.

Controller cannot go to server Side in mvc

I am doing my application in MVC. I have registration and Login links. I have implemented Login link in all pages. If i click login it is moving to the server side(controller) and opening. MY problem is from whatever page i click login it needs to open in the same window in popup. It means that it doesn't go the server side.
My code is
#model SYTMain.Models.Login
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout_for_login.cshtml";
//Layout = "~/Views/Shared/_Layout_for_login_registration .cshtml";
}
<center><h2>Login</h2></center>
<div id="dialog-modal" title="Login">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Login failed. Check your login details.");
<div style=" margin-bottom: 400px;">
<fieldset>
<legend>Login</legend>
<div class="editor-label">
#Html.LabelFor(u => u.EmailID)
</div>
<div class="editor-field">
#Html.TextBoxFor(u => u.EmailID)
#Html.ValidationMessageFor(u => u.EmailID)
</div>
<div class="editor-label">
#Html.LabelFor(u => u.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(u => u.Password)
#Html.ValidationMessageFor(u => u.Password)
</div>
#*<div class="editor-label">
#Html.CheckBoxFor(u => u.RememberMe)
#Html.LabelFor(u => u.RememberMe)
</div>*#
<input type="submit" value="Log In" />
</fieldset>
</div>
}
</div>
Layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
#*<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />*#
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script src="~/Scripts/Popup/jquery-1.5.1.min.js"></script>
<script src="~/Scripts/Popup/jquery-ui-1.8.11.js"></script>
#Scripts.Render("~/bundles/modernizr")
<script>
$(function () {
$("#dialog-modal").dialog({
width: 400,
height: 200,
show: {
effect: "shake",
duration: 100
},
hide: {
effect: "explode",
duration: 1000
}
});
});
</script>
</head>
<body style=" margin: 0px auto;overflow: scroll; overflow-x: hidden; /* width: 1330px; */height: auto;">
<div class="layoutouter">
<div class="layoutlogo">
#Html.ActionLink("Sell Your Time", "Index", "Home")
</div>
<div class="layoutmenu">
#if (!string.IsNullOrEmpty(Convert.ToString(Session["EmailID"])))
{
#Html.ActionLink("Signout", "Logout", "CU")
}
else
{
#Html.ActionLink("Register", "Create", "CU")
}
</div>
<br /><br />
#*<strong>Welcome #Session["EmailID"]</strong>*#
<div>
#RenderSection("featured", required: false)
</div>
</div>
<div style="width:1000px ; margin:0px auto;">
#RenderBody()
</div>
<div class="layoutfooter">
<div class="layoutfooter_data">
<div class="layout_location">
#Html.ActionLink("Change Location", "yy", "zz")
<span>|</span>
</div>
<div class="layout_feedback">
#Html.ActionLink("Feedback", "yy", "zz")
<span>|</span>
</div>
<div class="layout_help">
#Html.ActionLink("Help", "yy", "zz")
</div>
</div>
<div class="footer_copy">
<p>© #DateTime.Now.Year - acutesoftsys</p>
</div>
<div class="footer_condition">
<div class="footer_term">
<span>|</span>
#Html.ActionLink("Term & Condition", "", "")
</div>
<div class="footer_policy">
#Html.ActionLink("Privacy Policy", "yy", "zz")
</div>
</div>
</div>
#RenderSection("scripts", required: false)
</body>
</html>
My controller code is
[HttpPost, ValidateInput(false)]
public ActionResult Login(Login loginDetails)
{
if (ModelState.IsValid)
{
using (SYTEntities context = new SYTEntities())
{
var LoginUser = context.tblUsers.Where(a => a.EmailID == loginDetails.EmailID && a.Password == loginDetails.Password).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(loginDetails.EmailID, loginDetails.RememberMe);
Session["EmailID"] = LoginUser.EmailID;
Session["UserID"] = LoginUser.UserID;
return RedirectToAction("CalendarView", "Appt", new { CustomerUserid = Session["UserID"]});
// return RedirectToAction("Details/" + Session["UserID"]);
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");
}
}
}
return View(loginDetails);
}
Please help me to achieve this .
Thanks in Advance
Your controller code should look something like this
public ActionResult YourControllerAction( int Userid )
{
//Add your logic here
return PartialView( "UserDetails", model );
}
Your partial view should look like this
#model Models.Login
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>login</title>
</head>
<body>
<div>
/*Your markup here*/
</div>
</body>
</html>
Your jQuery code should look something like this.
$('#loginlinkid').on('click', function(evt) {
var $loginDiv = $('#PopUpDiv')
$.get(urlOfYourAction, function(data) {
$loginDiv.replaceWith(data);
});
//Add code to open popup here. eg..bootstrap modal dialog
});
Similar post here Render a partial view inside a Jquery modal popup on top of a parent view

How to get a rating value in asp.net mvc4?

I am new asp.net mvc4 with entity frame work, I have designed rating in cshtml file,Pls help me to get a rated value in Controller. Thanks in advance.
This is my cshtml code for rating
{
#{
ViewBag.Title = "Index";
}
<h2>Index rating</h2>
<h2>rating</h2>
#*<form method="post" id="signin" action="#Url.Action("rating", "Rating")">*#
#if (Request.IsAuthenticated)
{
<form method="post" id="signin" action="#Url.Action("rating", "Rating")">
<p>
#DateTime.Now
</p>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="~/Scripts/jquery.js"></script>
<script type="text/javascript" src="~/Scripts/rating.js"></script>
<link rel="stylesheet" type="text/css" href="~/Styles/rating.css" />
<script type="text/javascript">
$(function () {
$('.rating').rating();
$('.ratingEvent').rating({ rateEnd: function (v) { $('#result').text(v); } });
});
</script>
<input type="text" class="ratingEvent rating5" #*id="result"*# value="rating" />
<div><b id="result">5</b> start(s)</div>
<p> </p>
</form>
}
}
This is my Controller code
{
[HttpGet]
public ActionResult rating(int ratedvalue)
{
using (var db = new Project.Models.EntitiesContext())
{
var value= new Project.Models.Tbl_Rating();
var rat = db.Tbl_Rating.FirstOrDefault(u => u.Rating == ratedvalue);
value.Rating = Convert.ToInt32(rat);
return View();
}
}
}
}
try like this
View:
<form method="post" id="signin" action="#Url.Action("rating", "Rating")">
**YOUR CODE**
<input type="text" class="ratingEvent rating5" name="rating" value="rating" /> //Add name attribute
<input type="submit" />
</form>
Controller:
public ActionResult rating(FormCollection form)
{
int ratedvalue=form["rating"]
}