MVC select model's data from javascript - javascript

I am passing a model IEnumerable to a view. Appending the model to a dropdownlist
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
<p id="result"></p>
I have javascript on change I am getting value selected
<script>
$(function () {
$("#ddlOffers").change(function () {
alert(this.value);
});
});
</script>
It is retrieving the correct value Id. On selecting from the list I want grab the record details from a Model (such as Title,CreatedBy...etc) based on the selection.
How do I select the right data from the Model using value Id selected in the javascript? and should I then append the data to the p tag? Am I on the right track? Or is there a simpler solution?
Thanks for reading.

What #Html.DropDownList do is generate html like this:
<select id="ddlOffers" name="ddlOffers">
<option value="somevalue">sometext</option>
... for all your options
</select>
And if you just need the value selected, there's a shortcut in jquery:
<script>
$(function () {
$("#ddlOffers").change(function () {
alert($(this).val());
});
});
</script>
Or if you need anything other than the value, you can get the selected <option> itself by
<script>
$(function () {
$("#ddlOffers").change(function () {
console.log($(this).find("option:selected"));
console.log($("#ddlOffers option:selected")); //both of them do the same thing
});
});
</script>

suppose your model is
public class Model {
public int Id,
public string Title,
public int CreatedBy
/*Other Properties*/
}
when you put it through this statement
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
All you get on the html side and you can check the source of the HTML file is
<select>
<option value="1">Title 1</option>
<option value="2">Title 2</option>
<option value="3">Title 3</option>
<option value="4">Title 4</option>
<option value="5">Title 5</option>
</select>
So you see the problem in getting other properties is that they dont exist in the HTML page and hence cannot be directly retrieved by the javascript.
What you can do instead is put all the data you need in the html attributes in the html option element by creating it manually.
#foreach(var m in Model)
{
#m.Title
}
now when you will handle the change even the data will be available inside the HTML and hence you will be able to access it. With something like this
<script>
$(function () {
$("#ddlOffers").change(function () {
var createdBy = $(this).data('createdBy');
alert(createdBy);
});
});
</script>
Alternatively what you can do is and this approach will only help you if you want to later convert this into a big application.
after selecting the value in the javascript you send a ajax request to another action on your server with will return you all the fields you need back.
Update:-
3. You can also inject the model serializing it to JSON in the view and then whenever required accessing the info using js. For this i generally use Newtonsoft Json (install-package newtonsoft.json) then inside the view do something like this
<script>
var model = #JsonConvert.SerializeObject(Model);
</script>

The way I have approached this before is to use a form like this:
#using (Ajax.BeginForm("ActionName", "ControllerName",new AjaxOptions{HttpMethod = "POST"}))
{
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
<button type="submit">Submit</button>
}
Have the form submit to a controller and dropdown's value set to your ID field and then when it posts back into the controller, get the full object based on ID

Related

Store data-select value of href link in local storage and use it to select dropdown option on new page

I have some links in my navigation bar dropdown that all direct to the same page, but depending on the link that was clicked, it should select a specific select box option on this page. I decided to store the href link value in local storage and call the value when the linked page is loaded using jQuery, but I get the message "null" when the new page is loaded.
This is the html of the navigation bar dropdown links:
Jackets
Shoes
Shirts
JavaScript to store selected value in local storage:
window.onload = function() {
var linkInput = $('a[href="newpage.php"]').click(function () {
($(this).data('select'));
localStorage.setItem("storelinkInput",linkInput);
}
JavaScript in newpage.php:
window.onload = alert(localStorage.getItem("storelinkInput"));
var $select = $('#selector');
$select.val("storelinkInput");
HTML of select box in newpage.php:
<form>
<select id="selector">
<option value="option1">Jackets</option>
<option value="option2">Shoes</option>
<option value="option3">Shirts</option>
</select>
</form>
Honestly I am not sure if it is the best solution to use local storage for this purpose, or if it would be better to use PHP for this. Any suggestions that would point me in the right direction are much appreciated!
Thanks to Lars' comment I could fix the code and now it is running. In case someone is looking for a solution to this or a similar question here is the functional code:
This is the html of the navigation bar dropdown links:
Jackets
Shoes
Shirts
JavaScript to store selected value in local storage:
$(document).ready(function(){
$('a[href="newpage.php"]').click(
function () {
var toStore = $(this).data('select');
localStorage.setItem("storelinkInput", toStore);
});
});
HTML of select box in newpage.php:
<form>
<select id="selector">
<option value="option1">Jackets</option>
<option value="option2">Shoes</option>
<option value="option3">Shirts</option>
</select>
</form>
JavaScript in newpage.php:
$('#selector').val(localStorage.getItem("storelinkInput"));
It is important to place the second javascript ("$('#selector').val...") after the select box in the html/PHP file.

Passing Variables from one page to another

Im trying to pass a value from one page for a product to another page for the cart.
I've tried a few different options but haven't managed to come up with any solution.
I'm new to html and javascript so need a simple solution if thats possible so that I can understand.
Product Page
<label for="exampleFormControlSelect1">Example select</label>
<div>
<select class="form-control" id="Selected">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
<button id='btn' type="button" class="btn btn-secondary">Add To Cart</button>
<script type="text/javascript">
var value=0;
function send_selected(){
var selector = document.getElementById('Selected');
var value = selector[selector.selectedIndex].value;
sessionStorage.setItem(value);
}
document.getElementById('btn').addEventListener('click',send_selected);
</script>
Cart page
<script type="text/javascript">
var value = sessionStorage.getItem("value");
document.getElementById('display').innerHTML = value;
</script>
<body>
<div id="display"></div>
</body>
I would need to value from the drop down to be passed to the cart page to work out the value for all the users products selected.
You need to add two arguments to sessionStorage: key and value. Something like this:
sessionStorage.setItem("selectValue", value);
Also, as far as I know if you work with local html files opened like path/cart.html in the browser, the sessionStorage can't help you; it's scope is limited to the page. If you serve them through localhost, you'll be alright.
If this pages have different url, you can do it with query params: https://en.wikipedia.org/wiki/Query_string
By Browser Storage Method :
As mentioned by #Ferenc, the setItem method of session storage takes two parameters.
sessionStorage.setItem("selectedItem","value");
or you can use
sessionStorage["selectedItem"] = "value";
And to retrieve the value anywhere else in the browser you can either use the getItem() method or you can go with the array like value access approach i.e.
var value = sessionStorage["selected"];
But I would suggest you go with localStorage instead of sessionStorage, Because of it's larger scope than the sessionStorage scope.
You can read difference b/w session storage and local storage here.
Note: You can check for errors in your javascript code(Which now occurs when you call the getItem method with a single parameter ) by looking in the browser console.
By Query Parameters:
Well, this is not a recommended method if you are not using any server-side language. i.e. Java, PHP etc.
In this case, you append the query string in url. i.e.
http://www.url.com?value=selected
To Read how to access query parameters by using javascript refer to this question.
It worked for me to add to the 1st HTML file:
where_from = document.getElementById("where_from").value;
sessionStorage.setItem("pass_to_other_form", where_from);
and then to the 2nd HTML file:
var from_other = sessionStorage.getItem("pass_to_other_form");

jsp jump url parameters' names are the html elements' names

I write web front page page.jsp:
<select id="type_label" name="type_label">
<option value=""></option>
<c:forEach items="${types}" var="type" varStatus="status">
<option value="${type}">${type}</option>
</c:forEach>
</select>
function dosearch(){
var type_label = document.getElementById("type_label");
var tagVal = type_label.options[type_label.selectedIndex].value;
window.location="${ctx}/content/query?tag="+tagVal;
}
In controller Controller.java:
I get the data rows of mysql and put these data rows in List list.
Then put the list in model:
model.add("list", list);
The list has data rows in my log.
Then the controller make the page jump to page.jsp.
The project use rose java web frame.
return "content/page";
It make the page jump to page.jsp.
But the url is:
http://127.0.0.1:3428/web/content/page?type_label=%E6%90%9E%E7%AC%91&currentPage=
The url is expected to be:
http://127.0.0.1:3428/web/content/page?tag=%E6%90%9E%E7%AC%91&currentPage=
The url's parameter is type_label and not tag.
But type_label is select html element's id.
Why?Please give me a hand.Thanks a lot!
I know the reason about it.
After dosearch() executed, got the list of the tag from mysql.
Then jumped to content/page.jsp by
return "content/page";
The page would load by the form:
<form action="${ctx}/content/page" method="get" name="Form" id="Form"
class="form-horizontal">
It would get data list from mysql again. Because it got tag parameter by the tag element's name "type_label".
Then its url was "..type_label=tagname". The controller's method didn't get tag parameter from "type_label". So it had no tag parameter now.
It would get data list without tag.
So the data list was not the data of this tag.
Solution:
The tag element in HTML is that:
<select id="tag" name="tag">
<option value=""></option>
<c:forEach items="${tag}" var="tag" varStatus="status">
<option value="${tag}">${tag}</option>
</c:forEach>
</select>
Modify the dosearch() method to this:
function dosearch(){
$("#form").submit();
}
And modify the controller code to get tag parameter. Like that:
#Get("page")
public String page(Model model, #Param("tag") String tag){
...
}
The controller will get tag parameter by the tag element's name "tag".
After dosearch() executed, the controller will get tag parameter from the form.
Then get the data list of this tag in controller. And add list to model.
At last the page will show the list of the tag.

process web2py results in javascript

Complete newbie to web2Py.... I have a web page that has a dropdown menu and I want to perform certain queries based on the value selected.
Reports.html
<h2>Reports</h2>
<p>Please select a report template or choose to write your own.</p>
<select id="ReportSelect" onchange="ReportSelectionChange()">
<option disabled selected value="0"></option>
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
<script language="javascript" type="text/javascript">
function ReportSelectionChange()
{
var menuItem = document.getElementById("ReportSelect").value;
switch(menuItem)
{
case "1":
{{=myform}}
break;
case "2":
default:
alert(menuItem);
break;
}
}
controller python file
def reports():
user_id = request.args(0)
tuple = db(/*My query here*/).select()
myform = FORM('/*not sure what goes here*/')
return dict(tuple=tuple, myform=myform)
I want to pass back all the results from the query to the calling page and have the results appear in a table.
Q: How can I do this? what needs to get passed back? can this even be accomplished with javascript?
You are mixing HTML generated by web2py with javascript in a way that will not work. Remember that javascript is executed client side and python is server side.
In this case I suggest you start with trapped links:
http://www.web2py.com/books/default/chapter/29/12/components-and-plugins#Trapped-Ajax-links-and-the-A-Helper
Which will work well for your usage of either browsing or creating. Later you can revisit this page and make it better.
Use ajax function, the ajax function will be executed in some event ( this case onclick of the select item , then will run some method in your controller, this method in controller will return the data from db and the ajax function have parameter that means the target that result will be appended .
1.Use the ajax function on option element indicating that will executed on onclick event.
2. In method in your controller make the search on database and return the result.
3. Set the target of ajax function to some element in your html ( table , li's ...)
1.
<select id="ReportSelect" name="myoption">
<option disabled selected value="0"></option>
<option value="1" onclick="ajax('{{=URL('controller', 'method')}}', ['myoption'], 'your_target')" />option 1</option>
<option value="2">option 2</option>
</select>
2.
def method():
data = request.vars.myoption
your_result_query = db(your_query)
elements = UL(LI(content) for i in your_result_query)
return dict(result=elements)
In your view put a element with id with same name of target of ajax_function .

how can i implement a onclick in scriptlet?

I want to check which value I selected in a scriplet, when I press some value in the drop down list. How can I do that?
I tried as follows : ( below two codes are in the same page "test.jsp" )
code : for list
<select id="stream" name="current_session" onclick="fun2()" >
<option value="Winter">Winter</option>
<option value="Monsoon">Monsoon</option>
</select>
code : scriplet inside a javascript ( note that both html, scriplet are in the same page )
<script>
function fun2(){
<%
String given_session=request.getParameter("stream");
system.out.println(given_session);
%>
}
note : I am getting output as null, instead of selected session value. So how can get the selected values in scriplet which is in the same jsp page?
you can use a js to select the value
function get_the_value(){
var e = document.getElementById('stream').value;
return e;
}
In your web browser you have only html, javascript and css. All JSP code is meant to be run on the server. So you get only the output of the jsp file. And after this you cannot change the jsp code.

Categories