Getting data from a .cs file to a .cshtml - javascript

I'm trying to pass the data received from my function to a .cshtml file that uses javascript.
public static int LastID()
{
int LastArticleNr;
SqlConnection conn = GetSqlConnection(null);
conn.Open();
LastArticleNr = conn.QueryFirstOrDefault <int> ("SELECT CAST(isnull(last_value,0) AS INT) AS ID FROM sys.identity_columns WHERE object_id = OBJECT_ID('Artikel')");
conn.Close();
return LastArticleNr;
}
Now I don't know whether this is possible or not, or whether I would need to use a different method of getting this data. However what I've tried is simply calling the function which, to probably no-ones surprise didn't do much. I've also tried this:
#using namespace.Classes.DataLayer;
#{
var LastID = DataLayer.LastID();
}
However even if the using clause should include the class in which this function exists, it fails to recognise the DataLayer class.

It really depends on how your application is structured. Like: What error do you get when you try to access the Data Access Layer?
But If this is being done on page load, you could pass the data into TempData:
TempData['LastId'] = LastID();
And then in your razor page:
#{
var lastId = TempData['LastId'];
}
However if you wanted to get it at any time after the page has loaded and do not want to refresh the page, you would have make an ajax call

Related

on page load call controller method using data from query string

Is it possible to retrieve query string data on page load using javascript?
Let me explain my sample project in steps::
I have a view page showing tabular data. On button press, it retrieves id of the row and calls javascript function.
This javascript function, getDetails(id) has to call another view page, say Application.cshtml.
I have to pass the value of id and a variable message to this view page Application.cshtml.
I am trying to pass this as query string.
Now in this view page Application.cshtml, I have to retrieve the value of id and call contoller method to show the details of the id on page load.
Is it possible to do using javascript?
function getDetails(id)
{
var message = "testing";
var id_ = id;
window.location = "/FirmModels/Application/" + id_;
}
My problem is how can I retrieve the value of id and call controller method on page load using javascript in Application.cshtml?
Your question is a bit unclear but as far as I understood this question you can do this in two ways.
Assuming that you have something like this in your JS file.
window.location = "/Controller/Application?id= " + id_;
In the first method, the View inside your Controller will look like this
public ActionResult Application()
{
string id= Request.QueryString["id"];
//Do your operations here
return View();
}
The second way to do this to pass the id as a mandatory parameter to the view.
public ActionResult Application(string id)
{
return View();
}

How to access IMemoryCache from C# and Javascript

I stored values in my cache using my Controller class using the dependency IMemoryCache. I am also accessing my cache and get few values from it like so:
//IMemoryCache initailized before this variable : _cache
public void foo()
{
var token = _cache.Get<TokenModel>("Token" + HttpContext.Session.GetString("TokenGuid"));
//Do something with token
}
Question is:
How can I can access the cache from my Javascript file?
Cache is located on the server while JavaScript is executed on the client. The only way I can think of is if you create a cache controller and create a Get action on it. After that you would call this action in Ajax and asynchronously get the server cache value.
public class CacheController : Controller
{
[HttpGet("{key}")]
public IActionResult GetCacheValue(string key)
{
var cacheValue = //get your cache
return Json(cacheValue);
}
}
IMemoryCache allows you to speed up your application by storing your data "in-memory". So you can reach memory from your javascript code.
Please have a look to the documentation of the IMemoryCache here: https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.1
What I would suggest you is get your cached data on backend side and put it cookie. Then later you can get cookie value from your javascript code.
I assume you have an instance of IMemoryCache which name is _cache.
You can set cache by like this.
_cache.Set(cacheKey, cacheEntry, cacheEntryOptions);
HttpCookie myCookie = new HttpCookie("yourCookieName");
myCookie["cacheData"] = cacheEntry;
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
or you can do the same after you get your cached data. Just get the data from your memory and set it to cookie.
You can get the cookie from your Javascript by using both DOM or JQuery.
If you would like to use DOM:
var x = document.cookie;
For jquery have a look at this answer on StackOverFlow:
https://stackoverflow.com/a/1599367/1261525

Variable not being set when using a C# property in an MVC view

i'm sorry if its a newbie question but can anyone tell me why can't I set a value of a var to a c# property ?
i am trying to find a way to use the value to retrieve some model properties & do a calculation ....
#using System.Collections
#using System.Runtime.Serialization
#using CarRentalMVCApp.Models
#model CarRentalMVCApp.Models.Rentals
#functions {
public string selection { get; set; }
public decimal Price { get; set; }
}
#{
ViewBag.Title = "Create";
}
<script>
function select() {
var $el = $("#selectedCar");
var selected = $("#selectedCar option:selected").text();
$el.on("change", #selection = selected);
alert(#selection);
}
function Rental() {
var choice = select();
#foreach (var car in ViewData["availableCars"] as IEnumerable<Vehicles>)
{
if (selection != null && int.Parse(selection) == car.מספר_רכב)
{
Price = car.עלות_ליום_השכרה;
}
}
if (firstDay != null && lastDay != null) {
var rentalData = {
price: #Price,
firstDay: $("#beginRental").val(),
lastDay: $("#endRental").val()
}
alert(rentalData);
}
}
</script>
the #selection always equals 0 and ones I try to set it with another veriable like so:
#selection = selected;
it remains 0 !!!
I also cant understand why I can't use any type of javascript variable if the # sign is involved , would appresiate an explanation if you have the time or the links to help .....
MVC views are simply templates; there is not any sort of interoperation between C# and JavaScript. Rather, your C# variables simply cause text replacement. Therefore, these lines:
$el.on("change", #selection = selected);
alert(#selection);
...simply take the C# selection value and perform a substitution. So if selection is set to "foo" in the C#, the JavaScript that is output is:
$el.on("change", foo = selected);
alert(foo);
The event handler syntax for the change event is incorrect even if this did work. Plus, you cannot have JavaScript assign a value to a C# property. Rather, JavaScript will have to submit a form or perform an AJAX request to send data back to the server for processing, where it's handled by an MVC controller.
You cannot set a C# variable value in your client side code like the way you tried. Because when razor executes, it executes the C# code in it (at server) and the result of that (which could be string) will be send to the client to render the markup needed for the page.(Check the view source of the page).
So if you need to use this in your server code, you need to make an ajax call and send it to server
So if you want the price of the selected item value, make an ajax call to your server and send the selected option value and using that calculate the price and return it.
var selected = $("#selectedCar option:selected").text();
$.get("#Url.Action("GetPrice","Home")"?id="+selected ,function(res){
alert("Price of selection" + res);
});
Assuming GetPrice accepts a parameter with name id and returns the price
public ActionResult GetPrice(int id)
{
// based on this id, Get the corresponding price
decimal price = 100.0M; //replace with your value from db
return Json(price,JsonRequestBehavior.AllowGet);
}
Short answer:
The # means that it's server code, not client code. It gets executed before the page is sent to the user. Once the server finishes and the user gets the page, javascript code get executed.

Passing data from MVC controller to Angular view without showing the data value in the final html

I am working a MVC+angular front end project. In one scenario, the angular page will be launched with a HTTPS GET request, so, it display a log in page. In another scenario, we will get HTTPS POST request with user name and password in the post data. In this case, we need to have the MVC controller pass these information to the angular controller, and start the angular page view differently. I read several articles on how to pass data from MVC controller to the angular controller, angular view. Here is what I have
MVC controller:
public class HomeController : Controller
{
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index(string name, string password)
{
if (name == null)
{
name = "test";
password = "pass";
}
UserInfoModel infoModel = new UserInfoModel(name, password);
var model = SerializeObject(infoModel);
return View(model);
}
public static IHtmlString SerializeObject(object value)
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonTextWriter(stringWriter))
{
var serializer = new JsonSerializer
{
// Let's use camelCasing as is common practice in JavaScript
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
// We don't want quotes around object names
jsonWriter.QuoteName = false;
serializer.Serialize(jsonWriter, value);
return new HtmlString(stringWriter.ToString());
}
}
Index.cshtml
<!DOCTYPE html>
<html ng-app="MVCApp" ng-controller="LandingPageController">

<body>
<h1>{{models.username}}</h1>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
#Scripts.Render("~/bundles/MVCApp")
#model IHtmlString
<script>
angular.module("MVCApp", []).value("data", #Html.Raw(Model));
</script>
</body>
</html>
Angular application MVCApp.js is like:
var MVCApp = angular.module('MVCApp', []);
MVCApp.controller('LandingPageController', LandingPageController);
Angular controller is like:
var LandingPageController = function ($scope, data) {
console.log(data);
$scope.models = {
username: data.userName
};
}
LandingPageController.$inject = ['$scope', 'data'];
When I run it, I can see the data did get passed to the LandingPageController. But if I look at the html of the page, I see the following in the html.
angular.module("MVCApp", []).value("data", {userName:"test",password:"pass"});
I don't won't the data(at least some portion, like password) to be visible/readable in the html.
Can I pass the data without having it visible in the html?
#Html.Raw(Model) outputs the contents of your model when the page is rendered.
If you load the data via a separate ajax call after the page has loaded (and not with #Html.Raw(Model)), then it won't be visible by viewing the page source.
It can still very easily be found with a javascript debugger, so this will do absolutely nothing in terms of security. But if someone views the source, they won't see pages of JSON data.
The other downside is that you're making the user wait longer instead of providing the initial data when the page is first served.
Also, I don't know what you're ultimately trying to do, but passing cleartext passwords to a browser is almost never correct.

Get data from JS variable and set in a ASP.NET variable

I want to pass data from one user control to another one, but i've tried several things to do it, and non of them worked, such as sessionStorage in JS, Session in ASPX, cookies in both of them.
This data is dynamic so I don't now how to transfer it, to the other user control.
I even tried to put aspx code in the javascript function (then when I click in the button it could trigger the code, but it doesn't work as well).
This button i refereed above is written in a literal control.
JavaScript Functions
this function is the LoadUsers UserControl
function getID(ID) {
sessionStorage.setItem("userID", ID);
}
this function is in the Access UserControl
function catchIP() {
var ID = sessionStorage.getItem("userID");
$('#<%= value.ClientID %>').val(ID);
}
UserControls
Load Users:
...
string _str = "<a href'#lastAccess' css='btn btn-success' onclick='javascript:getID(" + _id[_contForeach] + "); catchID();'>Access</a>";
_loadUsers.Controls.Add(new LiteralControl(_str));
Access:
How can I get access to the ID in the JavaScript function and apply it without using Page_Load
To pass information between the server side code and the client side code (JavaScript) use ajax
Ajax
So using jquery, have something like this function:
$.get('getuserid.aspx', function(response) {
//Do something with return response
});
then in the code behind getuserid.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
//set userid
Response.ContentType = "text/plain";
Response.Write(userid);
Response.End();
}

Categories