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();
}
Related
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
Guys i have problem to get data from variable after execute rest in my controller. Here is sample to show my problem.
Controller
#RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, #PathVariable("id") Integer id)
{
model.addAttribute("message", "why this isn't working...");
return "redirect:/drawdiagram";
}
JavaScript drawdiagram.html
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
/*]]>*/
</script>
Result
Anyony can tell me why i have null there?
I really don't know what is going on :(
Maybe this is bad way? I have chosen thymeleaf but maybe there is some other way?
All i need to do is:
1. Click button.
2. Execute some backend code and get data to variable in controller.
3. Redirect to other page.
4. Execute some JavaScript code which is based on that variable.
.
Sources:
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart
Setting up a JavaScript variable from Spring model by using Thymeleaf
you are redirecting to another controller drawdiagram, the values in model object won't be available in other controller. So here you need to set the value first using either RedirectAttributes#addFlashAttribute or RedirectAttributes#addAttribute, and then get the value in the other controller -using #ModelAttribute("message").
#RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, #PathVariable("id") Integer id, RedirectAttributes redirectAttributes)
{
redirectAttributes.addFlashAttribute("message", "why this isn't working...");
return "redirect:/drawdiagram";
}
#RequestMapping(value = "drawdiagram", method = RequestMethod.GET)
public String OtherController(#ModelAttribute("message") String message, Model model) {
model.addAttribute("message", message);
return "drawdiagram";
}
I'm working on an ASP.NET MVC web application.
There is a view with a bunch of search filters and there is also a grid in the middle of the page that represents the result of the search.
End-user set value for the search filter and when search button clicked an ajax call returns the values that will rebind the gird.
every row in the grid represents 'ItemId' and 'version' which could be selected by the checkbox.
At the end when the user clicks on "Detail report" we need to redirect the user to another page(view).
I need to pass the selected search filters and the grid selected rows values as an array like this (ItemIds[] and Versions[]) to the "Detail" action.
So, to make the question clear. I need to pass the below values to the action :
search filters
ItemId array
Version array
Unfortunately, I can not pass the parameters to the action. I got null
I can not call the action as ajax call When i use
View (Index.cshtml)
function prepareSelectedInfos() {
var formValues = $('#form').serializeFormToObject();
var gridValues = GetGridSelectedValues();
var dto = {
FormFilters: formValues,
ItemIds : gridValues.ItemIds,
Versions : gridValues.Versions
}
return dto;
}
$('#lnkDetailReport').click(function () {
var gridValues = GetGridSelectedValues();
var url = '/Report/Controller/Detail/';
var dto = prepareSelectedInfos();
window.open(url + dto, '_blank');
});
Controller
public ActionResult Detail(ModelVersionStatisticalDetailDto data)
{
//create a ViewModel according to the incoming data
var viewModel = ;
return View(viewModel);
}
Model
public class ModelVersionStatisticalDetailDto
{
public ModelVersionStatisticalReportDto FormFilters { get; set; }
public int [] ItemIds { get; set; }
public string[] Versions { get; set; }
}
I need to have the view prepared values in the Detail action
To the best of my recollection, it is not possible to perform a redirect after having post a complex object in ajax call (with the same posted parameters).
In order to perform your desired operation, you can choose a solution from below.
Use query strings in your Detail action and perform a simple post action instead of ajax call
Try to replace the response of Detail action with Partial View
If you are seeking a client side solution, you can assist from localStorage object (a tricky solution). You can store the required data in a localStorage object and pass the key to the controller. In the target page, use the key in order to fetch the data stored in storage. Do not forget to clear it after the process. https://blog.logrocket.com/the-complete-guide-to-using-localstorage-in-javascript-apps-ba44edb53a36/
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.
I have created a WebMethod (dt) in code behind page c# of default.aspx page, i want to display response data(json string) on another page like default2.aspx page and bind json response data using ng-repeat angularjs
[WebMethod]
public static string getJson()
{
string data = string.Empty;
data = (string)HttpContext.Current.Session["getData"];
return data;
}
WebMethod defined in default.aspx.cs,
I want to bind json data(getting from webmethod) using ng-repeat angularjs in default2.aspx page from button click on default.aspx page. I am getting json string on same page, but don't know that how to show this on another page.
Any suggestion or help....
Just use something like the follwing on your second page i.e Default2.aspx
$.ajax({
url: 'Default.aspx/getJson',
.
.
});