how to get Session in javascript from ASP.NET MVC - javascript

I have some belows , please help me how i can get Session in Javascript code from Controller ?
public ActionResult Login(FormCollection f)
{
string sAcount = f["txtAccount"].ToString();
string sPassword = f.Get("txtPassword").ToString();
tblCustom cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);
if (cs != null)
{
Session["Account"] = cs;
return View();
}
return View();
}
and JS code is
<script >
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
alert('Hello' + Session["Account"] );
});
<script/>
the result is alert stil is not working, help me.

You should not update sessions many times, the type of data stored in Sessions are User Roles, Page Permissions and other global information. Once the login is done you should set login cookie. For login, you should use FormsAuthentication cookie.
Follow set Forms authentication to set forms authentication cookie.
Or check this link Create Forms Authentication cookie.
In the page use
alert("#HttpContext.Current.User.Identity.Name");

Although this doesn't directly answer your question, the preferred approach is to create ViewModels while passing and retrieving parameters.
Create a LoginViewModel:
public class LoginViewModel {
public tblCustoms Customs { get; set; }
//other stuff you have, you might consider moving account and password here too,
//instead of capturing with textbox names
//public string Account { get; set; }
//public string Password { get; set }
}
Pass that instead to the view.
public ActionResult Login(FormCollection f)
{
string sAcount = f["txtAccount"].ToString();
string sPassword = f.Get("txtPassword").ToString();
var cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);
if (cs != null)
{
Session["Account"] = cs;
//return View(); you don't need this line
}
return View(new LoginViewModel() { Customs = cs });
}
Add to top of your view:
#model YourNameSpace.LoginViewModel
And in the javascript:
<script>
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
alert('Hello ' + #Model.Customs );
});
<script/>
As an alternative to all of these, you can use ViewBag.
In the controller method, assign it to any name:
ViewBag.Customs = cs;
Then call it in the view:
alert('Hello ' + #ViewBag.Customs );
In order to use Session in your view, try this:
#Session["Account"].ToString();

Related

Calling script from Blazor with parameters

I've been given a script function and would like to partially translate it to C# in a Blazor app
<script>
function pay() {
var token = document.getElementById('token').value;
var card = document.getElementById('card').value;
var exp = document.getElementById('exp').value;
var cvv = document.getElementById('cvv').value;
var paymentData = {
ssl_txn_auth_token: token,
ssl_card_number: card,
ssl_exp_date: exp ,
ssl_cvv2cvc2: cvv
};
ConvergeEmbeddedPayment.pay(paymentData);
return false;
}
</script>
I want to call the script (that is inside the script above)
ConvergeEmbeddedPayment.pay(paymentData);
Directly from c# . Like so
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", paymentData);
There is some good information here:
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
But it stops short of helping me.
What kind of variable should I pass in the paymentData parameter? And how should I pass it?
I've tried var , object and string and also tried JsonSerializer.Serialize( ); but no luck
Based on suggestion from #BurningKarl I tried Dictionary and object[] but
I get an error saying the content is missing or "Expected BEGIN_OBJECT but was STRING "
Looks like you have to create your own c# class that mimics the payment data object in your Javascript.
Something like this
public class PaymentData
{
public string ssl_txn_auth_token {get; set;}
public string ssl_card_number{get; set;}
public string ssl_exp_date{get; set;}
public string ssl_cvv2cvc2{get; set;}
}
Then you have to create an instance of this class and pass it to InvokeVoidAsync as an argument.
var data = new PaymentData ()
{
ssl_txn_auth_token = "authtokenvalue",// you have to get it from control
ssl_card_number = "card number",
ssl_exp_date: "date", // probably it should be daytime or similar
ssl_cvv2cvc2 = "111"
}
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", data);

How to create a javascript model to send to an MVC controller?

I have a website served from a proprietary C++ server.
There is a standard javascript ajax function in the code but I don't want to start editing it.
The actual sending bit is as follows:
this.send=function(myawesomemodel)
{
/*Code redacted for brevity*/
obj.req.open('POST',myawesomeurl,true);
obj.req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
obj.req.send(JSON.stringify(myawesomemodel));
}
It used to send key value pairs as a query string but now it needs to send json.
I can send this function a controller/action address (myawesomeurl) for the appropriate end point and I can send it an awesome object which will be accepted by the action as a basic C# Model (myawesomemodel):
public ActionResult myawesomeaction(MyAwesomeClass myawesomeclass)
{
}
For the .Net model:
public class MyAwesomeClass
{
public int A { get; set; }
public int B { get; set; }
public string C { get; set; }
}
How do I build a javascript object the controller will recognise please?
Here's my latest failure:
function MyAwesomeModel()
{
this.A=1;
this.B=2;
this.C='Three';
}
Then:
var anawesomemodel=new MyAwesomeModel();
myawesomeajaxmodel.send(anawesomemodel);
I cannot construct the correct object in plain javascript so the mvc action registers it, what's the correct method please?
var myawesomemodel = {
A : 1,
B : 2,
C : 'Three'
}
For anyone else with the same problem who finds this page, Stephen Muecke nailed it
Change the ajax object to:
this.send=function(myawesomemodel)
{
/*Code redacted for brevity*/
obj.req.open('POST',myawesomeurl,true);
obj.req.setRequestHeader('Content-type','application/json;charset=utf-8');
obj.req.send(JSON.stringify(myawesomemodel));
}

How to Dynamically Render a javascript file for Users with different level of roles in Asp .Net MVC 5

Recently I got into Trouble with JavaScript in ASP.Net MVC5
My Issue like this I want to Render a script with functions and templates of html for users using same page(say Index.cshtml )
It should be dynamically rendered based on user account in identity system.
I tried string type of JavaScript code as profile information for user and render it using script tag in user view. The Controller with return type of JavaScript.
It Works But I need a Better Implementation of it.
[HttpPost]
public async Task<ActionResult> Atom(HttpPostedFileBase postedFile)
{
string filePath = string.Empty;
string userScript = string.Empty; ;
if (postedFile != null)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
//Read the contents of CSV file.
userScript = System.IO.File.ReadAllText(filePath);
}
var user = await UserManager.FindByEmailAsync(User.Identity.Name);
if (user == null)
{
return HttpNotFound();
}
user.cscript = userScript;
UserManager.Update(user);
return RedirectToAction("Cscript");
}
And here is my Controller for Js result
public JavaScriptResult js(string email)
{
var user = UserManager.FindByEmail(email);
return JavaScript(user.cscript);
}

How to use page session value and function in Jquery webmethod

I have a session value and a function in a apsx.cs page and I am using jquery webmethod to insert data into database.
Now i want to access session value and function in webmethod but it gives some error.
Below is my Page load code:
int nUserId = Convert.ToInt16(Session["UId"]);
And a Function :
public int CalcUser()
{
return Convert.ToInt16(Session["UId"]) * 2;
}
Now below is my Webmethod:
[WebMethod]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}
So how can I use session value and function in webmwthod.
Thanks
You need to explicitly state that you want to use Session with your ASP.NET AJAX Page Method by using the EnableSession= true value in the WebMethod attribute, like this:
[WebMethod(EnableSession = true)]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(HttpContext.Current.Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}
Note: You must fully qualify the namespace of the session (HttpContext.Current.Session).
To use the CalcUser() function you need to make it static and fully qualify the Session object, like this:
public static int CalcUser()
{
return Convert.ToInt16(HttpContext.Current.Session["UId"]) * 2;
}
Note: ASP.NET AJAX Page Methods only have access to static methods, as there is no instance of the page (or any class for that matter).
You need to use [WebMethod(EnableSession = true)] on webmethod
Then you can use like Context.Session["key"]
[WebMethod]
[WebMethod(EnableSession = true)]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(Context.Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}

Function to add and remove a username

In my chat application project, I am trying to broadcast usernames to all the users whenever a new user is connected to a server. and remove a username whenever the user leaves the server. The below is the code which I have tried by going through tutorials. (please check the file.js file which is not showing the desired output)
Chat.cs (Working) --> Implements "Hub" class of SignalR
public class Chat : Hub
{
/* showing only related content */
static ConcurrentDictionary<string, User> _users = new ConcurrentDictionary<string, User>();
public override Task OnDisconnected()
{
var user = _users[Context.ConnectionId]; //user as ConnectionId
User removedUser; //new class object
_users.TryRemove(Context.ConnectionId, out removedUser);
return Clients.All.leave(user, DateTime.Now.ToString()); //dynamic expression
}
public void Joined()
{
User user = new User(Context.ConnectionId, Clients.Caller.username);
_users.TryAdd(user.ConnectionID, user);
Clients.All.joins(user.ConnectionID, user.Name, DateTime.Now); //dynamic expression
}
}
User.cs (Working)
public class User
{
public User(string ConnID, string Username)
{
Name = Username;
ConnectionID = ConnID;
}
public string Name { get; set; }
public string ConnectionID { get; set; }
}
file.js (not working)
var chatUsername = window.prompt("Enter Username:", ""); //username
var chat = $.connection.chat; //connection
//
chat.client.joins = function (ConnectionId, name, Date) {
ConnectionId = 1; /* given value to just test */
name = chatUsername;
};
chat.client.leave = function (user, date) {
user = ""; //making the string empty so that the disconnected user value will be lost.
};
//Here is the connection which calls the "Joined" function of the server (Chat.cs)
What should I write in file.js functions (joins and leave) so that I will get the desired result as I mentioned above. Before asking here, I have gone through this site which is doing the same but including additional javascript files(knockout.js and json) which I dont want to include.(bcos I am new to jquery).
In order to pass UserNames to the client you can take your dictionary and in your joined server side method you could change the SignalR line to be:
Clients.All.joins(_users.Values); //dynamic expression
Then the client version of joins would be:
chat.client.joins = function (users) {
for(var i = users.length - 1; i >= 0; i--) {
alert("User Name: " + users[i].Name + "\nUser Connection ID: " + users[i].ConnectionID);
}
};
Of course you can handle the user information differently than alerting it, but that's the gist of how to handle the data. Lastly, I'd recommend against passing down the connection ID to everyone because a third party could then easily hijack it.

Categories