How to get global variable and global function inside JavaScript - javascript

At the time of login to my app, I stored the login details and token details inside the session of a class. Now on my aspx page, I have to write a javascript function, which should check if the token got expired within 5 mins or minutes. If then I have to call an API to update the access token with a refresh token. This API I have written in a global class. How can I call this method inside JavaScript? and also how can I get the values stored in the session of the class (ex: login_token_expires_in) inside javascript?
`public class GlobalVariables
{
public int login_user_role = 0;
public string login_user_name = string.Empty;
public string login_user_id = string.Empty;
public string login_token = string.Empty;
public string login_refresh_token = string.Empty;
public int login_token_expires_in = 0;//1799 sec; 29.9833 minute//1799000
}
public class GlobalFunctions
{
private bool GetLoginTokenWithRefreshToken(string username, string refresh_token)
{
GlobalVariables obj_GlobalVariables = (GlobalVariables)HttpContext.Current.Session["objGlobalVariableClass"];
bool status = false;
string log_data = string.Empty;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(GlobalVariables.WebAPITokenURI);
HttpResponseMessage response =
client.PostAsync("e_token",
new StringContent(string.Format("grant_type=refresh_token&username={0}&refresh_token={1}",
HttpUtility.UrlEncode(username),
HttpUtility.UrlEncode(refresh_token)), Encoding.UTF8,
"application/x-www-form-urlencoded")).Result;
if (response.IsSuccessStatusCode)
{
string resultJSON = response.Content.ReadAsStringAsync().Result;
e_Token result = JsonConvert.DeserializeObject<e_Token>(resultJSON);
obj_GlobalVariables.login_token = result.access_token;
obj_GlobalVariables.login_refresh_token = result.refresh_token;
obj_GlobalVariables.login_token_expires_in = Convert.ToInt32(result.expires_in * 1000);//seconds to millisec
status = true;
}
else
{
status = false;
}
return status;
}
}`
When login success, stores the login details in GlobalVariables class
`GlobalVariables obj_GlobalVariables = new GlobalVariables();
obj_GlobalVariables.login_token = result.access_token;
obj_GlobalVariables.login_token_expires_in = Convert.ToInt32(result.expires_in*1000);//seconds to millisec
obj_GlobalVariables.login_refresh_token=result.refresh_token;
obj_GlobalVariables.login_user_name =result.login_user_name;
etc..`
Javascript on Page1.aspx
`<script type="text/javascript">
var idleSecondsTimer = null;
idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
//have to check if time after login >= login_token_expires_in - 5 seconds
//then need to call the function GetLoginTokenWithRefreshToken(username, refresh_token)
}
</script>`
I want to know how to get the c# global variables and functions inside javascript

stored the login details and token details inside the session of a class.
No, no, no!
You mean you create a class instance, and then SHOVE it into session() to be saved, right? I don't see any "session" in a class here - so this MUST be cleared up by you. You don't have global variables here. And you can't use a static class, since it will be shared/used/the same for all users.
And a global scoped variable will go out of scope. So, you mean you create a class instance, set the values, and THEN save into session(), of which THEN you can retrieve for use on subsequent post-backs.
As for using/having/enjoying those values client side?
Well, you have quite a few options.
You can create a web method that returns the values (so, that would be a client side ajax call).
Another way?
In some cases, I will not make a web method call, and simple shove that server side class into a simple (one) hidden field on the page. (you just shove in the class as serialized), and then client side can grab that simple string, de serialize it into a client side object, and once again, then js client side code on that given page has use of all the values of that class.
It really depends on how many pages, and where you need such values from js code, but I would think in most cases, a web method would be the way to go.
However, lets use the "simple" hidden field, and SEND the class to the client side.
So, say this simple code server side:
For this example, I just shoved all the code right into the existing web page (so you can even cut + paste and try this).
So, say this code:
public class cHotel
{
public string FirstName = "";
public string LastName = "";
public string HotelName = "";
public string Description = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadMyData();
}
}
void LoadMyData()
{
DataRow drHotel =
General.MyRst("SELECT * FROM tblHotelsA WHERE ID = 16").Rows[0];
cHotel MyHotel = new cHotel();
MyHotel.FirstName = drHotel["FirstName"].ToString();
MyHotel.LastName = drHotel["LastName"].ToString();
MyHotel.HotelName= drHotel["HotelName"].ToString();
MyHotel.Description = drHotel["Description"].ToString();
JavaScriptSerializer jsS = new JavaScriptSerializer();
this.HotelInfo.Value = jsS.Serialize(MyHotel);
}
And the client side markup is this (I do have jQuery, but that one selector could be replaced with getelementByID - the rest is only js code - not jQuery.
<asp:HiddenField ID="HotelInfo" runat="server" ClientIDMode="Static" />
<div style="padding:40px">
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="test1();return false;"
/>
</div>
<script>
function test1() {
var MyHotel = JSON.parse($('#HotelInfo').val())
alert("Hotel name = " + MyHotel.HotelName)
alert("Description = " + MyHotel.Description)
}
</script>
So, when I run this page, and click on the button, I get/see this:
So, the above is a great way to send the class to the page, its simple, and no fancy web methods or anything is required.
And kind of nice, since that hidden field is available to ANY and all routines in the client side js code. So, clean, little code, easy. And the hidden field will survive post-backs and round trips. So, simple, easy, clean, and very little code. and hiddenfield does have viewstate.
However, these days, a LOT of people would suggest that you use a web method, and thus that web method could called from any js code. But, you are now dealing with a asynchronous call, and more moving parts.
However, lets below the above posted c# code, lets add a mebmethod, and give that a shot, shall we?
So, after above code, we now have this:
[WebMethod()]
public static cHotel GetHotel()
{
DataRow drHotel =
General.MyRst("SELECT * FROM tblHotelsA WHERE ID = 16").Rows[0];
cHotel MyHotel = new cHotel();
MyHotel.FirstName = drHotel["FirstName"].ToString();
MyHotel.LastName = drHotel["LastName"].ToString();
MyHotel.HotelName = drHotel["HotelName"].ToString();
MyHotel.Description = drHotel["Description"].ToString();
return MyHotel;
}
Ok, so now in client side, we will call the above web method (ajax call).
So, this:
function test2() {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetHotel",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { },
success: function (response) {
var MyHotel = response.d;
alert("Hotel name = " + MyHotel.HotelName)
alert("Description = " + MyHotel.Description)
},
failure: function (response) {
alert(response.d);
}
});
}
Again, the result would be the same. so, either the "hidden field" trick, or a standard webmethod (that's a end point) call will work.
And I suppose you could make some "single" webmethods that reutrn ONLY one value out of the class. Do keep in mind that while the web methods are "static" (it does not have use of controls on the web page, it can have use of session()).
So, say this:
[WebMethod(EnableSession = true)]
public static cHotel GetHotel()
{
DataRow drHotel =
bla bla bla

Related

Pass array values from JavaScript to my MVC C# application

I would like to pass array values from javascript to my C#.
Currently I am getting GUID null in C#. Not sure where I am doing wrong.
When I check developer tool, I have values
http://localhost/mvc/CheckData?GUID[]=C71F952E-ED74-4138-8061-4B50B9EF6463&ColumnVal=1&RowVal=1
I would like to receive this GUID value in my C# code.
JavaScript
function CheckData(obj) {
$.ajax({
data: {GUID:eArray, ColumnVal: $('#DisColumn').val(), RowVal: $('#DisRow').val()},
url: "/mvc/CheckData",
cache: false,
success: function (result) {
....
}
});
}
C# backend code to receive values from front-end.
public ActionResult CheckData()
{
var GUID = HttpContext.Request["GUID"];
int columnVal = Convert.ToInt32(HttpContext.Request["ColumnVal"]);
int rowVal = Convert.ToInt32(HttpContext.Request["RowVal"]);
string result = (Services.CheckDataRecords(rowVal, columnVal,GUID)) ? "true" : "false";
return Content(result);
}
Currently, I am getting null when it hits to C# method var GUID = HttpContext.Request["GUID"];.
I can see array value in front-end. But it is somehow not passing that value.
HttpContext.Request represents the request, and to access query data, you will need to do something like this: HttpContext.Request.Query["GUID"].
A more straightforward approach is to let ASP.NET do the work for you is just turn your C# backend to this:
[HttpGet("CheckData")] //change the route based on your code
public ActionResult CheckData([FromQuery] Guid[] guid, int columnVal, int rowVal)
{
var GUIDs = guid;
int column = columnVal;
int row = rowVal;
.....//your code
}

How to sent JavaScript Objects from the Client-Side and how to receive and parse them in Spring Boot Back-end?

I have came and left this problem numerous times while trying to make my web apps and have gotten fed up with no results, to the point that I have to ask here, so please excuse me if I come off as venting... I am quite aggravated.
I am trying to send data in the form of key-value pairs from my client(vanilla js) to my back end(spring boot java). I have tried numerous ways of doing it but can't seem to find the correct way/combination to achieve what I want done. My current non-working code is as follows.
Client-Side JS
var object = {
'id' : 1,
'username' : 'jumpthruhoops',
'password' : 'melodysteez'
};
Axios
.post('http://localhost:8080/gameSchedule', JSON.stringify(object))
.then((response) => {
console.log(response.data);
});
Back-End Spring Boot/Java
#CrossOrigin
#RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getSchedule(#RequestBody String user) {
System.out.println(user);
return "test";
}
The following code is what I currently have that has given me any type of results close to what I'm looking for. It gives me the following printed line...
%7B%22id%22%3A1%2C%22username%22%3A%22tdellard1%22%2C%22password%22%3A%22sisters3%22%7D=
...which I believe is a hex code for the string object I passed into the parameter. I'm not sure if this is from Spring Boot, or if this is what JSON.stringify does. Since the User Object is a test object and actual object that I plan on passing in, is way more complex, I don't want to figure out how to decode the hex code, unless I can't get anything else going and I completely have to.
Because it is more complicated, I don't want to use a lot of #RequestParams("name") String VaribleName like 40 times in the parameter of the method. This was also the only other way to get results but passing those variables into a url is maddening.
Some other things I have tried are #ModelAttribute and (#RequestBody User user), both return errors, one that seems to be reoccurring is
018-10-30 23:38:29.346 WARN 12688 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
So what I am pretty much asking is for guidance on what is the best way to send my data from Axios(form.serialize, JSON.stringify, JavaScript Object, etc.) and what corresponding method I need to use to obtain that data on my Spring Boot Back-End and make it manipulative so I can turn it into a POJO.
Just remove JSON.stringify(object) and put object.
Axios
.post('http://localhost:8080/gameSchedule', object)
.then((response) => {
console.log(response.data);
});
You can see an example on POST request here axios documentation
On Spring boot you have to create an entity like this:
#Entity
public class UserAccount implements Serializable {
#Id
private Long id;
#Column(unique = true, nullable = false)
#Size(max = 255)
private String userName;
#Column(nullable = false)
#NotNull
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
and change your code for here
#CrossOrigin
#RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserAccount getSchedule(#RequestBody UserAccount user) {
System.out.println(user.getUserName());
return user;
}
If you are sending an object you have to use object when receiving at back-end side and make sure that name of the field in request object and the field name of the class at back-end side must be same,
so it should be like this:
I am just making some changing in your code to access field:
var data = {
'id' : 1,
'username' : 'jumpthruhoops',
'password' : 'melodysteez'
};
// name of variable(data variable) doesn't matter but inside everything consider as a body
axios.post('http://localhost:8080/gameSchedule', JSON.stringify(object), {
headers: {
'Content-Type': 'application/json',
}
}
);
back-end side retrieve fields
//create one Student class to map fields with body
#CrossOrigin
#RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getSchedule(#RequestBody Student student) {
System.out.println(student.id);
System.out.println(student.username);
System.out.println(student.password);
return "test"
}

How to refresh view when using signal r to update on database change

I'm using mvc, i have a dashboard for which i have used charthelper and bootstrap admin chart. Now i want to update the data on database change. For which i'm trying to use signal R.
Before
I used repository to get data from database. So had services folder which had methods for it.
Now.
I'm not sure exactly how to do it.
But what i have done so far is created a hub class,
returning
public static void Send()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<DashboardHub>();
context.Clients.All.updateOnDashboard();
}
and on view
<script>
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.dashboardHub;
$.connection.hub.logging = true;
chat.client.foo = function () { };
//debugger;
// Create a function that the hub can call to broadcast messages.
chat.client.updateOnDashboard = function () {
getAllDashboardUpdates()
};
$.connection.hub.start().done(function () {
getAllDashboardUpdates();
console.log('Now connected, connection ID=' + $.connection.hub.id);
})
.fail(function () { console.log('Could not connect'); });;
//$.connection.hub.stop();
});
function getAllDashboardUpdates() {
$.ajax({
url: '/Dasdhboard/Index',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
//$("#refTable").html(result);
}).error(function () {
});
}
controller method
public ActionResult Index(int? page)
{
IEnumerable<test> newlist = null;
newlist = GetAlltest();
var data = dashboardService.GetDashboardData(page, User);
if (newlist != null)
{
return View(data);
}
return View(data);
}
to search for dependency
public IEnumerable<test> GetAlltest()
{
var messages = new List<test>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT [id],[testid] FROM [dbo].[test]", connection))
{
command.Notification = null;
SqlDependency.Start(_connString);
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new test { id = (int)reader["id"] });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
DashboardHub.Send();
}
}
Even after doing it my view is not refreshed. I'm sure code is redundant. CAn someone show me a better way to do it. Or where i'm going wrong.
This is just one method. I have 2 charts too.
If I understand your code correctly you currently establish a SingalR connection and if receive a updateOnDashboard() on the client firing a AJAX call to get a full HTML view from the server in insert it in the DOM using jQuery.
I would change that so that updateOnDashboard() also receives your new values and render these values on the client side instead calling again the server for HTML code. I would go even further and create a Javascript view-model for those values and using Knockout to databind your dashbord elements to the view-model. The updateOnDashboard() then simply needs to push these values (parameters) into the view-model and the HTML gets updates by Knockout.
I've blogged about some of this in this post... or V2 post
What I don't see in your code is a peace of code that detects these data-updates. You need something on the server that detecting the changes and sends out those updateOnDashboard() calls.
Please also note that your Hub method Send() is not used anywhere. Hub methods are only used for client-to-server calls (incoming server calls). You probably don't have these so you will not need a hub method - I guess.
Update based on your comment:
I use SinglaR for "live" broadcasting newly added log-items to the web-clients. On the server-side I have a singleton that tests for new data and broadcast them to the web-clients using SignalR. Here the code:
/// <summary>
/// Singleton that periodically checks the log database for new messages and broadcasts them to all
/// connected web-clients (SignalR).
/// </summary>
public class LiveMessageTicker : ILiveMessageTicker, IRegisteredObject
{
private readonly TimeSpan updateInterval = TimeSpan.FromMilliseconds(2000);
private readonly ILogEntriesRepository repository;
private Guid lastLogEntryId = Guid.Empty;
private readonly SemaphoreSlim checkSemaphore = new SemaphoreSlim(1, 2);
private Timer checkTimer;
private readonly IHubContext hub;
/// <summary>
/// Initializes a new instance of the <see cref="LiveMessageTicker"/> class.
/// </summary>
/// <param name="repository">The database repository to use.</param>
/// <exception cref="System.ArgumentNullException"></exception>
public LiveMessageTicker(ILogEntriesRepository repository)
{
if (repository == null) { throw new ArgumentNullException(nameof(repository)); }
this.repository = repository;
// Register this instance to in ASP to free it up on shutdown
HostingEnvironment.RegisterObject(this);
// Get the server-side SignalR hub
hub = GlobalHost.ConnectionManager.GetHubContext<ServerMonitoringHub>();
// Configure a Timer that calls CheckForNewMessages all 2 sec's
checkTimer = new Timer(CheckForNewMessages, null, TimeSpan.Zero, updateInterval);
}
/// <summary>
/// Stops this instance.
/// </summary>
/// <param name="immediate">if set to <c>true</c> immediatelly.</param>
/// <seealso cref="IRegisteredObject"/>
public void Stop(bool immediate)
{
checkTimer.Dispose();
checkTimer = null;
HostingEnvironment.UnregisterObject(this);
}
private void CheckForNewMessages(object state)
{
if (checkSemaphore.Wait(500))
{
try
{
// Get new log entries
var newLogEntries = repository.GetNewLogEntries(lastLogEntryId).ToList();
// If there arent any new log entries
if (!newLogEntries.Any())
{
return;
}
lastLogEntryId = newLogEntries.Last().Id;
// Convert DB entities into DTO's for specific client needs
var logEntries = newLogEntries.Select(l => new
{
id = l.Id,
correlationId = l.CorelationIdentifier,
messageId = l.MessageId,
time = l.Time.ToLocalTime(),
level = (int)l.Level,
messageText = l.Message,
additionalData = l.AdditionalData.Select(a => new { name = a.Name, value = a.Value }).ToArray(),
tags = l.Tags.Select(t => t.Name).ToArray(),
channel = l.Channel.Name,
username = l.Username,
workstation = l.WorkstationName
}).ToList();
// Broadcast all new log entries over SignalR
hub.Clients.All.addLogMessages(logEntries);
}
finally
{
checkSemaphore.Release();
}
}
}
}
This all gets started in Global.asax.cs there I create a single instance of the above class (which registers itself by ASP.Net for proper stopping later on with HostingEnvironment.RegisterObject(this)).
Please note that I don't push rendered HTML-Code or Views to the client. I push the data as JSON. The server does not render it but the client does. To render it on the client I use a Javascript/Typescript view-model that collects the incomming messages in a Knockout ObservableArray. This observablearray is bound to in HTML using the Knockout foreach (see here). So for the data-updates I don't use Razor and ASP.Net to generate the HTML. This is all part of the initially sent view which has data-bindings in it and refers my Javascript/Typescript. It's quite similar as documented in the above liked blog-post.

How to get Data from Model to JavaScript MVC 4?

that's my function:
<script> function Calculate()
{
var ItemPrice = document.getElementById("price");
var weight = document.getElementById("weight");
var SelWeight = weight.options[weight.selectedIndex].value;
alert(SelWeight);
var Category = document.getElementById("SelectedCategory");
var SelCategory = Category.options[Category.selectedIndex].value;
alert(SelCategory);
}
</script>
i want to get SelCategories.Tax and SelCategories.Duty to add them to weight value and total price to show the total in a label.. I'm using ASP.NET MVC 4 and this is my Model that i want to use
public class CategoriesModel
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public decimal Duty { get; set; }
public decimal Tax { get; set; }
public IEnumerable<SelectListItem> CategoriesList { get; set; }
}
I think the best approach here is to use Json and something like Vue.js, Knockout.js, etc. (but also you can do it without these libraries, if your case is simple).
First, you need to install Json support with a command in PM console:
PM> install-package NewtonSoft.Json
Then, in your view you can convert your model to javascript object like this:
#model ...
#using Newtonsoft.Json
...
<script type="text/javascript">
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model));
</script>
Then you can access all the properties in your model with in plain JavaScript:
var id = data.CategoryID;
That's it! Use knockout (update 2018: this is obsolete, there is no reason you should use knockout now) if your logic is complicated and you want to make your view more powerful. It could be a little bit confusing for newbie, but when you get it, you'll gain the super-powerful knowledge and will be able to simplify your view code significantly.
You need to create actions (methods in the controller) that return JsonResult.
From the client side, make ajax calls to the server to recover and use that data. The easiest way to do this is to use any of the jQuery ajax methods.
public JsonResult GetData(int id)
{
// This returned data is a sample. You should get it using some logic
// This can be an object or an anonymous object like this:
var returnedData = new
{
id,
age = 23,
name = "John Smith"
};
return Json(returnedData, JsonRequestBehavior.AllowGet);
}
When you use a jQuery get to the /ControllerName/GetData/id, you'll get a JavaScript object in the success callback that can be used in the browser. This JavaScript object will have exactly the same properties that you defined in the server side.
For example:
function getAjaxData(id) {
var data = { id: id };
$.get('/Extras/GetData/1', // url
data, // parameters for action
function (response) { // success callback
// response has the same properties as the server returnedObject
alert(JSON.stringify(response));
},
'json' // dataType
);
}
Of course, in the success callback, instead of making an alert, just use the response object, for example
if (response.age < 18) { ... };
Note that the age property defined in the server can be used in the JavaScript response.
If you prefer a class try jsmodel. After converting the mvc view model to javascript it adds the benefit of retrieving DOM updates.
var jsmodel = new JSModel(#Html.Raw(Json.Encode(Model)));
Then anytime you want to get the latest state of the DOM do this to update your variable:
var model = jsmodel.refresh();
Website:
http://chadkuehn.com/jquery-viewmodel-object-with-current-values/
There is also a nuget:
https://www.nuget.org/packages/jsmodel/
var errors = '#Html.Raw(Json.Encode(ViewData.ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)))';
var errorMessage=JSON.parse(errors);

Reading from localStorage, passing it to the server through JSON and creating a session from it in MVC3

Roughly what I am trying to implement is a login system for a website that allows for the usage of a guests account, storing their data in localStorage. If they click on the button to log in as a guest, it will attempt to read through localStorage for any previous data that might exist before passing it off to the server so it can create a session and rely on that session for returning a view based on that data. This likely isn't the most efficient way of handling it but if the users log in with an account instead of as a gust, it will retrieve information from a database so it has to work in conjunction with that.
Just to establish what is happening server-side, it's something akin to iGoogle where a list of URLs are supplied by the user and it will return a webpage containing a scrollable wall of iFrames of those URLs. If they're logged in with an actual ccount, their data is stored in the database as well as the session and if they're logged in as a guest, their data is stored locally as well as the session. This could again probably be optimized to allow for less reliance on the session variable server-side but I'm focusing on getting it working first and then I can optimize it.
View: (Contains some debugging code still)
<div id="LocalStorageStatus"></div>
<script type="text/javascript">
var isGuest = false;
if (Modernizr.localstorage) {
$('#LocalStorageStatus').html('<button type="input" onclick="guest()" id="guest">Log in as guest</button>');
function guest() {
localStorage["Guest"] = true;
var URLarray = new Array();
if(localStorage["URL"] != "0")
{
for(var i = 0; i < localStorage["URL"]; i++)
URLarray[i] = localStorage["URL" + i];
}
var data = {
ID : 'local',
URL: localStorage["URL"],
URLList : URLarray,
Template: localStorage["Template"]};
$.ajax({
url: '#Url.Action("Guest","Login")',
data: JSON.stringify(data),
success: function () { alert("YOU ARE A GUEST!") },
error: function () { alert("YOU ARE NOT A GUEST!") },
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json'
});
}
}
else {
$('#LocalStorageStatus').html('Guest log-in requires an HTML5-compatible browser.');
}
</script>
Model:
public class GuestUser
{
public string ID { get; set; }
public int URL { get; set; }
public List<string> URLList { get; set; }
public int Template { get; set; }
}
Controller: (For a temporary view that will establish the session before redirecting them to the area for logged-in users)
[HttpPost]
public ActionResult Guest(GuestUser guest)
{
Session.SetDataInSession("ID", guest.ID);
return RedirectToAction("../Frames");
}
Right now, it seems to be creating and passing the JSON object just fine, though it does return a failure despite setting the session ID, but I don't want to proceed from here until I know that the JSON object is being built as I want it to be. Will this work with how I've implemented it and have I committed any major coding atrocities in the process?
As an alternative to this, I would like using a class object that stores the ID, an arraylist of URLs and an integer but I'm unsure of the complexity this might add to due to handling an object rather than easily definable variables.

Categories

Resources