Set Session Variable In MVC View and DateTimePicker - javascript

How can i set a Session value in the MVC View from Javascript in a DateTimePicker?
I have this code:
if('#Session["Data"]'==""){
$('#datetimepicker').datepicker('setDate', startDate); #Session["Data"] = startDate;}
else { $('#datetimepicker').datepicker('setDate', '#Session["Data"]'); }
This code work fine but the code
#Session["Data"] = startDate;
not working. How can i save Data here?
Thank you to all

You're merging javascript and c# code.
You can't set the startDate (javascript) to Session (c#) because javascript runs on client side.
If startDate is equals to DateTime.Now it'll help you.
<script>
if('#Session["Data"]'===""){
$('#datetimepicker').datepicker('setDate', new Date());
#(Session["Data"] = DateTime.Now);
} else {
$('#datetimepicker').datepicker('setDate', '#Session["Data"]');
}
</script>

Your C# Code in your razor view gets executed in server. But your javascript code executes on client. So you cannot set a c# variable value inside your javascript like what you have in your question.
What you can do is make an ajax call to an endpoint and set the value in session there. So create an action method to handle the ajax call
[HttpPost]
public ActionResult SetDate(DateTime date)
{
// Set to session here
return Json( new { Status="Success"});
}
Now from your javascript code, use ajax to call this endpoint and pass the date value.
var startDate= "Read the date value here";
$.post("YourControllerName/SetDate", { date = startDate},function(r){
if(r.Status==="Success")
{
alert("Date is now in session")
}
});
You may consider using the Url.Action helper method to generate the path o the action method instead of hardcoding.

Related

Passing spring java object to javascript

I want to pass a java object to javascript. I am using spring as backend. For html I just passed the object to my model and I can call them in html through the "$" parameter. But in javascript it seems that this will not work.
So my question is. How can I call a passed object (which is already a json string) in javascript?
// java side
model.addAttribute("data", jsonObject);
// javascript side
// ???
You need to use ajax and call the api in the from spring controller.
#RequestMapping(value = 'url', method = RequestMethod.methodType)
public #ResponseBody List < SomeClass > getAllData(pass parameter here) {
return someResultFromHere;
}
You should add an ajax call for that specific api endpoint and use the name of the model to extract anything with in.. As brk stated you will call it and it will get value.Then you can use that to parse the data comming from the beckend of your server this is an example of the code.
// java side
model.addAttribute("data", jsonObject);
//ajax side
$getJSON('http://<yourserverip>:<yourport>/myapi/values/', function(data){
console.log(data.<yourValue>);
});

Calling a controller function from onchange event in html view

I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this: "Jul 2017". There can be as many as 12 entries in the list.
When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.
How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.
I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.
Html View Code
#Html.DropDownList("selectList", Model.ReverseMonthsLists())
View Model Code
public IEnumerable<SelectListItem> ReverseMonthsLists()
{
var selectListItems = GetDates()
.Select(_ => _.ToString("MMM yyyy"))
.Select((dateString, index) => new SelectListItem
{ Selected = index == 0, Text = dateString, Value = dateString })
.ToList();
return selectListItems;
}
public static IEnumerable<DateTime> GetDates()
{
DateTime startDate = new DateTime(2017, 6, 1).Date;
var currentDate = DateTime.Now.Date;
int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
currentDate.Month - startDate.Month;
var dates = new List<DateTime>(numberOfMonthsToShow);
currentDate = currentDate.AddMonths(-1);
for (int i = 0; i < numberOfMonthsToShow; i++)
{
dates.Add(currentDate);
currentDate = currentDate.AddMonths(-1);
}
return dates;
}
Controller function
public ActionResult Report_Performance()
{
//var newDate = DateTime.Parse(strDate); //<- Use newDate as parameter value into aVar to replace date at the end of the string
var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
return this.View(aVar);
}
The normal way to get a value to a controller is for the user to post the page back to the server, e.g. via a submit button. When this happens, the controller's action method can receive the selected item as an argument and then do what it needs to do. So if you just want the user to submit the form, and allow the web site to render the next page based on the selected value (and a list that you compute based on that value), that is all you need to do.
On the other hand, perhaps you don't want the user to submit the page; you want a series of dates to be displayed within the page, or for the dates to be processed by code running in the browser. If that is the case, I would suggest you perform the computations in Javascript within the browser itself, thereby avoiding the need for a round trip. Nothing in your GetDates() method requires any server side data, so it's just a question of converting your c# code to Javascript code.
In some rare cases, you will want a UX element on the page to get updated immediately based on a server computation, without the page being posted. If that is what you want, you'll have to use the AJAX solutions the other posters have provided. It's much more complicated and much more work. If you don't need that, use one of the solutions I provided above.
You Can Use The OnChange EventHandler For The HTML Select Option
(The DropDownList ) To Start An Ajax Call To Your Controller , Simply Create a JavaScript Function That Preforms a Jquery Ajax Request Containing The User Selected Data To The Controller and Retrieve JSON From The Controller Using Return Json() Instead Of Return View() , Then Handle The Retrieved Data Using JavaScript , Your Controller Will Need To Accept a Parameter In Order To Receive The Data From The Ajax Request
function SendDataToController (TheDropDownName){
var DataToSend = $('#'+TheDropDownName).text();
// Or Pass `this` From The Html When Assigning The Event Listener
// and Do Something Like var DataToSend = this.text();
$.ajax({
url: "#(Url.Action("ActionName", "ControllerName"))",
data: DataToSend,
success: function(ResponseFromController){
//Do Stuff With Response
}
});
}
This Will Send The Data To Controller So You Should Receive It in A Parameter
public ActionResult MyAction (string DataToSend)
{
//Do Stuff With Data and Get a Json Object To Return
Return Json(JsonObject);
}
MVC Ajax Is Essential So You Should Learn It Before Tryin To Work On Any MVC Project, Also You Should Handle Request Error Using fail attr in The Ajax Setting But I Will Leave That To You

How to Create Session Variable in JavaScript MVC3 Razor View engine .cshtml

I am using MVC3 with Razor View engine,
i have .cshtml page in that i have a JavaScript function, inside that JavaScript function, i want to create Session variable and retrieve that session in same JavaScript function.
how to achieve this..
Description
The Session is on the server side so you need to call the server in order to set or retrieve session variables.
Just post to a controller and set the Session variable there.
Sample
jQuery
$(function () {
$.post('/SetSession/SetVariable',
{ key : "TestKey", value : 'Test' }, function (data)
{
alert("Success " + data.success);
});
});
Mvc Controller
public class SetSessionController : Controller
{
public ActionResult SetVariable(string key, string value)
{
Session[key] = value;
return this.Json(new { success = true });
}
}
More Information
Save and retrieve Session data via Ajax using JQuery in an MVC 3 application
To add a session with the javascript code. just must be to add this code
sessionStorage.setItem("MyId", 123);
and you can use this code to call the added session
var value = sessionStorage.getItem("MyId");

passing and retrieving variables in cakephp from javascript using GET METHOD

i know how to construct url parameters in javascript and i know how to extract it if im going to pass it to a php file.
However, here's the scenario, i am going to pass variables from javascript to a function. I have 2 textboxes and i can already get the values of these textboxes and store it to javascript variables:
var fname;
name = document.getElementById('fname');
var lname;
lname=document.getElementById('name');
now im stucked up on how i am going to construct it in a way that cakephp post method will be able to understand it. is it just the same with php like the code below?
var vars = "fname="+fname+"&lname="+lname;
here's my code:
if(window.XMLHttpRequest){
xmlVariable = new XMLHttpRequest();
}
else{
xmlVariable = new ActiveXObject("Microsoft","XMLHTTP");
}
xmlVariable.open("POST","save",true);
xmlVariable.send(vars);
"save" is actually a function in my cakephp where i wanna process the saving of "fname" and "lname" variables.
i need to do it in cakephp. Would there be any way?
Try with Params or data
Params variable is used to provide access to information about the current request.
public function save()
{
this->params['form']['lname'];
this->params['form']['fname'];
}
OR
Used to handle POST data sent from the FormHelper forms to the controller.
public function save()
{
this->data['lname'];
this->data['fname'];
}

Can JavaScript read HTTP Session object?

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?
(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.
As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

Categories

Resources